2022-08-06 17:34:50 +02:00
|
|
|
class RLEIterator {
|
2024-03-02 21:01:53 +01:00
|
|
|
private int[] encoding;
|
|
|
|
private int major = 0;
|
|
|
|
private int minor = 0;
|
|
|
|
|
|
|
|
public RLEIterator(int[] encoding) {
|
|
|
|
this.encoding = encoding;
|
|
|
|
}
|
|
|
|
|
|
|
|
private void nextSegment() {
|
|
|
|
major += 2;
|
|
|
|
minor = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
private int lastConsumed() {
|
|
|
|
if (major == 0 && minor == 0) {
|
|
|
|
// Haven't consumed anything
|
|
|
|
return -1;
|
|
|
|
} else if (major <= encoding.length && minor == 0) {
|
|
|
|
// Consumed last element of a previous segment
|
|
|
|
return encoding[major - 1];
|
|
|
|
} else if (major >= encoding.length) {
|
|
|
|
// Everything was consumed
|
|
|
|
return -1;
|
2022-08-06 17:34:50 +02:00
|
|
|
}
|
|
|
|
|
2024-03-02 21:01:53 +01:00
|
|
|
// Last consumed from the current segment
|
|
|
|
return encoding[major + 1];
|
|
|
|
}
|
2022-08-06 17:34:50 +02:00
|
|
|
|
2024-03-02 21:01:53 +01:00
|
|
|
public int next(int n) {
|
|
|
|
while (n > 0 && major < encoding.length) {
|
|
|
|
int consumed = Math.min(n, encoding[major] - minor);
|
2022-08-06 17:34:50 +02:00
|
|
|
|
2024-03-02 21:01:53 +01:00
|
|
|
n -= consumed;
|
|
|
|
minor += consumed;
|
2022-08-06 17:34:50 +02:00
|
|
|
|
2024-03-02 21:01:53 +01:00
|
|
|
if (minor == encoding[major]) {
|
|
|
|
nextSegment();
|
|
|
|
}
|
|
|
|
}
|
2022-08-06 17:34:50 +02:00
|
|
|
|
2024-03-02 21:01:53 +01:00
|
|
|
if (n > 0) {
|
|
|
|
return -1;
|
2022-08-06 17:34:50 +02:00
|
|
|
}
|
2024-03-02 21:01:53 +01:00
|
|
|
|
|
|
|
return lastConsumed();
|
|
|
|
}
|
2022-08-06 17:34:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-03-02 21:01:53 +01:00
|
|
|
* Your RLEIterator object will be instantiated and called as such: RLEIterator obj = new
|
|
|
|
* RLEIterator(encoding); int param_1 = obj.next(n);
|
2022-08-06 17:34:50 +02:00
|
|
|
*/
|