1. 문제(원본)
Given two arrays of integers nums and index. Your task is to create target array under the following rules:
- Initially target array is empty.
- From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
- Repeat the previous step until there are no elements to read in nums and index.
Return the target array.
It is guaranteed that the insertion operations will be valid.
Example 1:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2]
Example 2:
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4]
Example 3:
Input: nums = [1], index = [0] Output: [1]
Constraints:
- 1 <= nums.length, index.length <= 100
- nums.length == index.length
- 0 <= nums[i] <= 100
- 0 <= index[i] <= i
2. 문제
배열에 넣어야할 데이터 배열과 해당 데이터의 index의 배열을 받아 결과 배열을 출력하라.
3. 나의 답
class Solution {
func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
var result: [Int] = []
for (index, element) in index.enumerated() {
result.insert(nums[index], at: element)
}
return result
}
}
4. 다른 유저의 답
#1
class Solution {
func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
var target = [Int]()
target.reserveCapacity(nums.count)
for i in 0..<nums.count {
target.insert(nums[i], at: index[i])
}
return target
}
}
#2
class Solution {
func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
return nums.enumerated().reduce(into: [Int](), { $0.insert($1.1, at: index[$1.0]) })
}
}
5. 마무리
대부분의 답변은 비슷했지만 배울만한 답변을 가져왔다.
우선 reserveCapacity 아직까지 써본 적이 없기 때문에 새로운 학습이 되었다.
그 다음으로 reduce를 통한 한줄 코드..와 한 줄 코드를 생각을 해보았지만 여기까지 미치지 못했다.
reduce의 활용을 좀 더 학습해야 겠다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1470. Shuffle the Array (0) | 2020.07.28 |
---|---|
LeetCode1464. Maximum Product of Two Elements in an Array (0) | 2020.06.05 |
LeetCode1450. Number of Students Doing Homework at a Given Time (0) | 2020.05.18 |
LeetCode1431. Kids With the Greatest Number of Candies (0) | 2020.05.18 |
LeetCode821. Shortest Distance to a Character (0) | 2020.04.20 |