900. RLE Iterator Medium
1/**
2 * [900] RLE Iterator
3 *
4 * 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.
5 *
6 * For example, the sequence 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] are also valid RLE of arr.
7 *
8 * Given a run-length encoded array, design an iterator that iterates through it.
9 * Implement the RLEIterator class:
10 *
11 * RLEIterator(int[] encoded) Initializes the object with the encoded array encoded.
12 * int next(int n) Exhausts the next n elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1 instead.
13 *
14 *
15 * Example 1:
16 *
17 * Input
18 * ["RLEIterator", "next", "next", "next", "next"]
19 * [[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]
20 * Output
21 * [null, 8, 8, 5, -1]
22 * Explanation
23 * RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].
24 * rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].
25 * rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].
26 * rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].
27 * rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
28 * but the second term did not exist. Since the last term exhausted does not exist, we return -1.
29 *
30 *
31 * Constraints:
32 *
33 * 2 <= encoding.length <= 1000
34 * encoding.length is even.
35 * 0 <= encoding[i] <= 10^9
36 * 1 <= n <= 10^9
37 * At most 1000 calls will be made to next.
38 *
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/rle-iterator/
43// discuss: https://leetcode.com/problems/rle-iterator/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47struct RLEIterator {
48 vec![]
49 }
50
51
52/**
53 * `&self` means the method takes an immutable reference.
54 * If you need a mutable reference, change it to `&mut self` instead.
55 */
56impl RLEIterator {
57
58 fn new(encoding: Vec<i32>) -> Self {
59
60 }
61
62 fn next(&self, n: i32) -> i32 {
63
64 }
65}
66
67/**
68 * Your RLEIterator object will be instantiated and called as such:
69 * let obj = RLEIterator::new(encoding);
70 * let ret_1: i32 = obj.next(n);
71 */
72
73// submission codes end
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn test_900() {
81 }
82}
83
Back
© 2025 bowen.ge All Rights Reserved.