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]
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]
Solution:
1. 建立 ans = []
2. 將 for(i < 2) 迴圈執行兩次
3. 將 for(j < nums.length)將每個 nums 的元素執行一次,並運用 .push() 放入 ans。
4. 回傳 ans。
Code.1: For Loop (BigO(2n)
var getConcatenation = function(nums) { let array = [] for (let i = 0; i < 2; i++) { for (let j = 0; j < nums.length; j++) { array.push(nums[j]) } } return array; }
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]
Example 2
Input: nums = [1,3,2,1] step.1 i = 0 ans.push(nums[0]) => [1] ans.push(nums[1]) => [1, 3] ans.push(nums[2]) => [1, 3, 2] ans.push(nums[3]) => [1, 3, 2, 1] step.2 i = 1 ans.push(nums[0]) => [1, 3, 2, 1, 1] ans.push(nums[1]) => [1, 3, 2, 1, 1, 3] ans.push(nums[2]) => [1, 3, 2, 1, 1, 3, 2] ans.push(nums[3]) => [1, 3, 2, 1, 1, 3, 2, 1] return and //[1, 3, 2, 1, 1, 3, 2]
Code.2: For Loop (BigO(n))
var getConcatenation = function(nums) { const length = nums.length for (let i = 0; i < length; i++) { nums.push(nums[i]) } return nums; }
Code.3: Concat (BigO(n))
var getConcatenation = function(nums) { return nums.concat(nums) }
.concat()
.concat():合併兩個或多個陣列。 const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]
Code.4: split (BigO(n))
var getConcatenation = function(nums) { s = nums.join(",") ss = s + "," + s return ss.split(","); }
Code.5: ...array (BigO(n))
var getConcatenation = function(nums) { return [...nums, ...nums]; }