1.문제
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
정수 배열 nums가 주어질 때 각 pair 별로 [freq,val] = [nums[2*i], nums[2*i+1]] 를 만족하게 끔 부분 배열을 만든다. 부분배열들을 모두 합친 배열을 리턴하면 되는 문제이다.
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] is [2,4,4,4].
Example 2
Input: nums = [1,1,2,3]
Output: [1,3,3]
Constraints:
- 2 <= nums.length <= 100
- nums.length % 2 == 0
- 1 <= nums[i] <= 100
2.풀이
- nums를 순회하면서 [i,j]를 받고 j가 i번 있는 array를 출력한다
- 순회가 끝나면 이를 합쳐 리턴한다
/**
* @param {number[]} nums
* @return {number[]}
*/
const decompressRLElist = function (nums) {
let result = [];
const helper = (freq, val) => {
// freq 횟수 만큼 val을 arr에 넣어서 리턴해주는 helper 함수
const arr = [];
for (let i = 0; i < freq; i++) {
arr.push(val);
}
return arr;
};
for (let i = 0; i < nums.length / 2; i++) {
const [freq, val] = [nums[2 * i], nums[2 * i + 1]];
result.push(...helper(freq, val)); // 각 pair 마다 helper로 생성되는 배열의 요소들을 result에 넣어준다
}
return result;
};
3.결과
