900. RLE Iterator
T: O(n), n is next() input n
S: O(encoding size)
class RLEIterator {
int[] nums;
int idx = 0;
public RLEIterator(int[] encoding) {
this.nums = encoding;
}
public int next(int n) {
while (idx < nums.length) {
if (n > nums[idx]) {
n -= nums[idx];
idx += 2;
} else {
nums[idx] -= n;
return nums[idx+1];
}
}
return -1;
}
}
/**
* Your RLEIterator object will be instantiated and called as such:
* RLEIterator obj = new RLEIterator(encoding);
* int param_1 = obj.next(n);
even i: encoding[i] tells times of
encoding[i + 1] repeated
arr = [8,8,8,5,5] can be encoded to be
encoding = [3,8,2,5].
encoding = [3,8,0,9,2,5] and
encoding = [2,8,1,8,2,5]
4
[3, 8, 0, 9, 2, 5]
n -= arr[idx]
idx+=2
arr[idx]-= n
return arr[idx+1]
*/
Last updated