首页 > Web开发 > 详细

1313. Decompress Run-Length Encoded List

时间:2020-07-04 14:07:21      阅读:61      评论:0      收藏:0      [点我收藏+]

问题:

给定一个数组,相邻两两元素构成编码,第一个元素代表出现次数,第二个元素代表出现的元素。

求编码前的原数组。

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

原文:https://www.cnblogs.com/habibah-chang/p/13234671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!