1929. Concatenation of Array
Problem
Return an array of length 2n that is nums followed by another copy of nums.
Example: [1,2,1] → [1,2,1,1,2,1]
Build nums + nums: allocate 2n slots and write each element twice, at i and i + n.
Complexity: O(n).
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + nums
assert Solution().getConcatenation([1, 2, 1]) == [1, 2, 1, 1, 2, 1]
assert Solution().getConcatenation([1, 3, 2, 1]) == [1, 3, 2, 1, 1, 3, 2, 1]
assert Solution().getConcatenation([5]) == [5, 5]
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] = ans[i + n] = nums[i];
return ans;
}
}
func getConcatenation(nums []int) []int {
return append(append([]int{}, nums...), nums...)
}