Dev/Algorithm

알고리즘 - Decompress Run-Length Encoded List

healthyryu 2020. 2. 2. 23:58

문제

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

문제 파악

: 역시 처음에 문제가 뭔지 파악하는데 시간이 조금 걸렸다. 영어로 써진 문제는 역시 문제 자체를 파악하는데 몇초, 몇십초, 몇분 등의 추가적으로 시간이 소요된다.

 

생각

: 배열이 짝수 개수로 온다. 배열에 들어온 값을 어디에 어떤 방식으로 담을 것인가?

 

답안

class Solution {
    fun decompressRLElist(nums: IntArray): IntArray {
        val value = ArrayList<Int>()
        for (i in 0..nums.size - 1 step 2) {
            for (j in 0..nums[i] - 1) {
                value.add(nums[i+1])
            }
        }
        
        return value.toIntArray()
    }
}

 

 

반응형