Skip to content

Commit 3843806

Browse files
committedJun 10, 2021
feat: use queue to store max
1 parent 4379e0a commit 3843806

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed
 

‎jump_game_vi/src/lib.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::collections::VecDeque;
2+
13
pub struct Solution {}
24

35
impl Solution {
@@ -14,10 +16,21 @@ impl Solution {
1416
同时需要再判断,如果 queue 中的第一个元素(nums 索引,对应最大值)超过了范围,则删除最大值。
1517
*/
1618
let mut max_cache = vec![0; nums.len()];
19+
let mut queue = VecDeque::new();
1720
for (i, n) in nums.iter().enumerate().rev() {
18-
let res_vec = max_cache[(i + 1)..(i + 1 + k as usize).min(nums.len())].to_vec();
19-
let res = res_vec.iter().max().unwrap_or(&0) + *n;
21+
let res = *n
22+
+ queue
23+
.front()
24+
.and_then(|x| max_cache.iter().nth(*x))
25+
.unwrap_or(&0);
2026
max_cache[i] = res;
27+
while !queue.is_empty() && max_cache[*queue.back().unwrap()] < res {
28+
queue.pop_back();
29+
}
30+
queue.push_back(i);
31+
if *queue.front().unwrap() > i + k as usize - 1 {
32+
queue.pop_front();
33+
}
2134
}
2235
max_cache[0]
2336
}

0 commit comments

Comments
 (0)
Please sign in to comment.