900. RLE Iterator
问题:
给定一个行程长度编码序列A,即偶数为代表下一位数的个数。
如A=[3,8,0,9,2,5],是序列【88855】的编码。
next(n)函数返回,对被编码序列消化n个数后最后消化的数值。实现初始化函数RLEIterator和next函数。
Example 1: Input: ["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]] Output: [null,8,8,5,-1] Explanation: RLEIterator is initialized with RLEIterator([3,8,0,9,2,5]). This maps to the sequence [8,8,8,5,5]. RLEIterator.next is then called 4 times: .next(2) exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5]. .next(1) exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5]. .next(1) exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5]. .next(2) exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1. Note: 0 <= A.length <= 1000 A.length is an even integer. 0 <= A[i] <= 10^9 There are at most 1000 calls to RLEIterator.next(int n) per test case. Each call to RLEIterator.next(int n) will have 1 <= n <= 10^9.
解法:
该问题是顺序消化序列,则使用queue来实现。
而queue对于元素修改是不利的,因此再使用vector来存储数据作为字典,queue来存取index即可。
代码参考:
1 class RLEIterator { 2 public: 3 queue<int> Seq; 4 vector<int> AA; 5 RLEIterator(vector<int>& A) { 6 AA=A; 7 for(int i=1; i<A.size(); i+=2){ 8 if(A[i-1]!=0){ 9 Seq.push(i); 10 } 11 } 12 } 13 14 int next(int n) { 15 while(!Seq.empty()){ 16 int p=Seq.front(); 17 if(AA[p-1]>=n){ 18 AA[p-1]-=n; 19 if(AA[p-1]==0) Seq.pop(); 20 return AA[p]; 21 }else{ 22 n-=AA[p-1]; 23 Seq.pop(); 24 } 25 } 26 return -1; 27 } 28 }; 29 30 /** 31 * Your RLEIterator object will be instantiated and called as such: 32 * RLEIterator* obj = new RLEIterator(A); 33 * int param_1 = obj->next(n); 34 */