Concatenation of Array
Given an integer array nums
of length n
, you want to create an array ans
of length 2n
where ans[i] == nums[i]
and ans[i + n] == nums[i]
for 0 <= i < n
(0-indexed).
Specifically, ans
is the concatenation of two nums
arrays.
Return the array ans
.
The problem is taken from :- leetcode Problem
Approach:-
1 | 2 | 1 |
Index position is = 0 | Index position is = 1 | Index position is = 2 |
The given Array is mentioned above.
Our final Array is:-
1 | 2 | 1 | 1 | 2 | 1 |
Index position is = 0 | Index position is = 1 | Index position is = 2 | Index position is = 3 which is(n+index position) where n is the length of the given array | Index position is = 4 which is(n+index position) where n is the length of the given array | Index position is = 5 which is(n+index position) where n is the length of the given array |
If we look closely, we can find a pattern. The value is repeating after (n+index position) in each loop of the array.
Code:-
class Solution {
public int[] getConcatenation(int[] nums) {
final int n = nums.length;
int[] ans = new int[n * 2];
for (int i = 0; i < n; ++i)
ans[i] = ans[i + n] = nums[i];
return ans;
}
}
For more problem solution, please visit:-Algorithm and Datastructure