코딩 테스트 풀이 🛠
[Leet Code - eazy] 1470. Shuffle the Array
엄성준
2023. 1. 28. 00:14
728x90
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
- 1 <= n <= 500
- nums.length == 2n
- 1 <= nums[i] <= 10^3
나의 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* @param {number[]} nums
* @param {number} n
* @return {number[]}
*/
var shuffle = function(nums, n) {
const x = nums.splice(0,n)
const answer =[]
for(let i=0; i<x.length; i++){
answer.push(x[i])
answer.push(nums[i])
}
return answer
};
|
cs |
문제를 풀며 느낀 점
- 먼저 nums.splice(0,n)을 통해서 nums배열에서 splice를 통해서 0번째 index부터 n번째 인덱스 까지 배열의 값을 변수 x에 할당하였습니다. 그렇게 되면 잘린값이 절반 앞부분은 x에 절반 뒷부분은 nums에 할당되었습니다. 그 후 for문을 통해서 0부터 배열 x의 길이만큼 반복을 하도록 했고 반복할 코드에는 return할 빈 배열 answer에 x에서 하나 nums에서 하나씩 할당받은 answer[]을 return 해주었습니다.
728x90