1313. Decompress Run-Length Encoded 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] 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

  

解法:

遍历编码数组,每次遍历取出一个编码对,两个元素 i+=2。

再循环出现次数freq次,将元素nums[i+1] push_back到结果中。

 

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> decompressRLElist(vector<int>& nums) {
 4         vector<int> res;
 5         for(int i=0; i+1<nums.size(); i+=2){
 6             for(int freq=nums[i];freq>0;freq--){
 7                 res.push_back(nums[i+1]);
 8             }
 9         }
10         return res;
11     }
12 };

 

1313. Decompress Run-Length Encoded List

上一篇:一个随时跟新的css库


下一篇:说说 HTTPS 的工作原理