1. 程式人生 > 實用技巧 >1313. Decompress Run-Length Encoded List

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 };