-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrle-iterator.rs
56 lines (48 loc) · 1.35 KB
/
rle-iterator.rs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#![allow(dead_code, unused, unused_variables)]
fn main() {
let mut s = RLEIterator::new(vec![3, 8, 0, 9, 2, 5]);
println!("{}", s.next(2));
println!("{}", s.next(1));
println!("{}", s.next(1));
println!("{}", s.next(2));
}
struct Solution;
#[derive(Debug)]
struct RLEIterator {
encoding: Vec<i32>,
index: usize,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl RLEIterator {
fn new(encoding: Vec<i32>) -> Self {
Self { encoding, index: 0 }
}
fn next(&mut self, n: i32) -> i32 {
let mut n = n;
for i in self.encoding.iter().skip(self.index).step_by(2) {
if *i == 0 {
self.index += 2;
continue;
}
match n.cmp(i) {
std::cmp::Ordering::Equal => {
let r = self.encoding[self.index + 1];
self.index += 2;
return r;
}
std::cmp::Ordering::Greater => {
self.index += 2;
n -= *i;
}
std::cmp::Ordering::Less => {
self.encoding[self.index] -= n;
return self.encoding[self.index + 1];
}
}
}
-1
}
}