We are given a run-length encoded list nums
. 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 = [1,2,3,4]
[2,4,4,4]
2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100
nums
always positive integers?
1 <= nums[i] <= 100
.nums
:
nums
is always even, and we will iterate through pairs of elements.[freq, val]
, generate a sublist containing freq
instances of val
.Here is the Java implementation for the problem:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public int[] decompressRLElist(int[] nums) {
List<Integer> result = new ArrayList<>();
// Iterate over the pairs in the input array
for (int i = 0; i < nums.length; i += 2) {
int freq = nums[i];
int val = nums[i+1];
// Add 'val' to the result 'freq' times
for (int j = 0; j < freq; j++) {
result.add(val);
}
}
// Convert the list to an array
int[] decompressedList = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
decompressedList[i] = result.get(i);
}
return decompressedList;
}
}
nums
of length n
once.freq
number of elements, ensuring linear traversal of the list input.m
, which is the total number of elements generated from the run-length encoded list.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?