Concatenation of Array easy
Problem Statement
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. Return the array ans
.
Example 1
Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
Example 2
Input: nums = [1,3,2,1] Output: [1,3,2,1,1,3,2,1] Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
Steps
- Create the result array: Initialize an array
ans
with a length twice that of the input arraynums
. - Copy elements: Iterate through the input array
nums
. For each element at indexi
, copy it toans[i]
andans[i + nums.Length]
.
Explanation
The problem requires creating a new array that contains the elements of the input array twice. The solution directly implements this by creating a larger array and copying the elements to the appropriate positions. The key is understanding that the second half of the new array is a direct copy of the first half.
Code
public class Solution {
public int[] GetConcatenation(int[] nums) {
int n = nums.Length;
int[] ans = new int[2 * n];
for (int i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
}
Complexity
- Time Complexity: O(n), where n is the length of the input array. We iterate through the input array once.
- Space Complexity: O(n), because we create a new array of size 2n to store the result. Note that the space used by the input array is not considered in the space complexity analysis.