1. 문제(원본)
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
2. 문제
주어진 2n의 정수형 배열에서 앞의 n집합 x와 뒤의 n집합 y를 번갈아 가면서 출력하라
3. 나의 답
class Solution {
func shuffle(_ nums: [Int], _ n: Int) -> [Int] {
var result: [Int] = []
for index in 0..<n {
result.append(nums[index])
result.append(nums[index + n])
}
return result
}
}
4. 다른 유저의 답
#1
class Solution {
func shuffle(_ nums: [Int], _ n: Int) -> [Int] {
return zip(nums, nums.dropFirst(n)).flatMap { [$0, $1] }
}
}
5. 마무리
이번 문제는 대부분의 답변들과 같았지만 역시나 한 줄로 끝낸 유저의 답변을 보고 아 방법이 있긴 있구나 하는 생각이 들었다. 속도면이나 메모리 면에서도 별 차이는 없었고 한가지 익숙치 않은 것은 저 zip, 많이 사용해보지 않아서 문제 풀 동안 생각지도 못했다. 좀 더 활용할 수 있도록 해서 앞으로의 문제에 좀 더 유연하게 대처할 수 있도록 해야 겠다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1528. Shuffle String (0) | 2020.07.30 |
---|---|
LeetCode1480. Running Sum of 1d Array (0) | 2020.07.30 |
LeetCode1464. Maximum Product of Two Elements in an Array (0) | 2020.06.05 |
LeetCode1389. Create Target Array in the Given Order (0) | 2020.06.05 |
LeetCode1450. Number of Students Doing Homework at a Given Time (0) | 2020.05.18 |