Problem
We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence.
- For example, the sequence
arr = [8,8,8,5,5]can be encoded to beencoding = [3,8,2,5].encoding = [3,8,0,9,2,5]andencoding = [2,8,1,8,2,5]are also valid RLE ofarr.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the RLEIterator class:
RLEIterator(int[] encoded)Initializes the object with the encoded arrayencoded.int next(int n)Exhausts the nextnelements and returns the last element exhausted in this way. If there is no element left to exhaust, return-1instead.
Example 1:
1 | Input |
Constraints:
2 <= encoding.length <= 1000encoding.lengthis even.0 <= encoding[i] <= 1091 <= n <= 109- At most
1000calls will be made tonext.
Analysis
这是一道数组的iterator题目,题目给出一个encoding数据,长度是偶数,encoding[i]表示的是encoding[i + 1]出现的次数,所以可以理解为相邻两个数字配对出现,前一个是次数,后一个是数字本身。
因此对于每对组合,我只需要把下标定位在第一个位置就可以得到两个信息了,而且这个下标只会指向偶数下标的位置,所以判断结束的条件是idx > size - 2。然后我们来看关键的逻辑是next(int n)这个方法,它要求的是向后遍历n个数字并返回最后的那个数字,那这里有两种情况,第一种是n比当前这个数字出现的次数要小,这个处理很容易,返回的结果就是当前的数字,然后更新下频率为arr[idx] -= n就可以了;第二种比较麻烦,因为当前这个数字的次数不足n,所以idx要往后移动,每次移动2位,移动前要把当前的频率arr[idx]置为0,同时每次移动完都要判断是否已经越界。
Solution
无。
Code
1 | class RLEIterator { |
Summary
这道题目难度比前两道要小,主要就是处理n比当前元素的频率大的情况,需要向后移动idx。这道题目的分享到这里,感谢你的支持!