forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRLE Iterator.java
42 lines (36 loc) · 1.14 KB
/
RLE Iterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class RLEIterator {
long[] prefixEncoded;
long processed = 0;
int l = 0;
public RLEIterator(int[] encoding) {
int encodeLen = encoding.length;
this.prefixEncoded = new long[encodeLen];
for(int i=0;i<encodeLen;i+=2) {
long prevPrefixSum = 0;
if(i > 0) {
prevPrefixSum = this.prefixEncoded[i-2];
}
this.prefixEncoded[i] = encoding[i] + prevPrefixSum;
this.prefixEncoded[i+1] = encoding[i+1];
}
}
public int next(int n) {
int r = this.prefixEncoded.length-2;
processed += n;
if(l >= this.prefixEncoded.length || processed > this.prefixEncoded[this.prefixEncoded.length - 2]) {
return -1;
}
while(l < r) {
int m = (l + ((r-l)/2));
if(m % 2 != 0) {
m = m - 1;
}
if(this.prefixEncoded[m] >= processed) {
r = m;
} else {
l = m + 2;
}
}
return l >= this.prefixEncoded.length ? -1: (int) this.prefixEncoded[l + 1];
}
}