1. 문제(원본)
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are a elements with value b in the decompressed list.
Return the decompressed list.
Example 1:
Input: nums = [1,2,3,4] Output: [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4,4] is [2,4,4,4].
Constraints:
- 2 <= nums.length <= 100
- nums.length % 2 == 0
- 1 <= nums[i] <= 100
2. 문제
Int형 배열을 받아 2개의 인덱스 씩 페어를 이루어 앞의 수 만큼 뒤의 값을 새로운 배열에 넣는다.
3. 나의 답
class Solution {
func decompressRLElist(_ nums: [Int]) -> [Int] {
var result: [Int] = []
for (index, element) in nums.enumerated() {
if (index+1) % 2 == 0 {
for _ in 0..<nums[index-1] {
result.append(element)
}
}
}
return result
}
}
4. 다른 유저의 답
#1
class Solution {
func decompressRLElist(_ nums: [Int]) -> [Int] {
var sol = [Int]()
for i in stride(from: 0, to: nums.count, by: 2) {
sol += Array(repeating: nums[i+1], count: nums[i])
}
return sol
}
}
5. 마무리
로직을 작성하는데는 큰 어려움은 없었지만 다른 유저의 답을 보고 배열 활용을 좀 더 했으면 하는 생각이 들었다.
stride와 repeating에 대해 공부를 할 수 있었다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1342. Number of Steps to Reduce a Number to Zero (0) | 2020.02.16 |
---|---|
LeetCode1295. Find Numbers with Even Number of Digits (0) | 2020.02.02 |
LeetCode977. Squares of a Sorted Array (0) | 2020.01.26 |
LeetCode709. To Lower Case (0) | 2020.01.26 |
LeetCode 905. Sort Array By Parity (0) | 2020.01.19 |