Given a list nums of integers, where nums[i] for all i is part of a run-length encoded list. For example, consider the list [freq1, val1, freq2, val2, ...] where each pair (frequencyn, valuen) means that val appears freq times. Construct and return the decompressed list.
nums guaranteed to be even?
nums is guaranteed to be even.nums be negative or zero?
freq) will always be positive integers, but the values (val) can be any integers.nums list in steps of 2, treating each pair of elements as (freq, val).val to the result list freq times.#include <iostream>
#include <vector>
std::vector<int> decompressRLElist(std::vector<int>& nums) {
std::vector<int> result;
for (size_t i = 0; i < nums.size(); i += 2) {
int freq = nums[i];
int val = nums[i + 1];
for (int j = 0; j < freq; ++j) {
result.push_back(val);
}
}
return result;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4};
std::vector<int> decompressedList = decompressRLElist(nums);
for (int num : decompressedList) {
std::cout << num << " ";
}
return 0;
}
n is the number of pairs (i.e., nums.size() / 2), and f is the average frequency of the values. The worst case occurs when the frequencies are large, causing many insertions into the result list.m is the total number of elements in the decompressed list. This includes the space required for the result 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?