LeetCode Js-1929. 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.
給予一個整數陣列 nums 和長度為 n,你想新增一個長度為 2n 的陣列 ans。
其中 ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
具體來說,ans 是兩次 nums 陣列的串聯。
回傳 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]
Solution:
Code:
var getConcatenation = function(nums) {
let ans = []
for (let i = 0; i < 2; i++) {
for (let j = 0; j < nums.length; j++) {
ans.push(nums[j])
}
}
return ans
}
FlowChart:
Example 1
Input: nums = [1,2,1]
step.1
i = 0
ans.push(nums[0]) => [1]
ans.push(nums[1]) => [1, 2]
ans.push(nums[2]) => [1, 2, 1]
step.2
i = 1
ans.push(nums[0]) => [1, 2, 1, 1]
ans.push(nums[1]) => [1, 2, 1, 1, 2]
ans.push(nums[2]) => [1, 2, 1, 1, 2, 1]
return ans //[1, 2, 1, 1, 2, 1]