0%

Leetcode 1313. Decompress Run-Length Encoded List

題目

1
2
3
4
5
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].

解法思維

1
2
3
4
5
6
7
8
9
10
11
12
var decompressRLElist = function(nums) {
let arr = [];
function pushTo(count, num) {
if (count === 0) return;
arr.push(num);
pushTo(count-1, num);
}
for (let i = 0; i < nums.length; i += 2) {
pushTo(nums[i], nums[i+1]);
}
return arr;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
var decompressRLElist = function(nums) {
let result = []

for(let i=0; i<nums.length; i+=2) {
const frequency = nums[i]
const value = nums[i+1]

// result = [...result, ...new Array(frequency).fill(value)]
result.push(...new Array(frequency).fill(value))
}

return result
};