Merge pull request #1550 from cezarbbb/Greedy02

添加 0045.跳跃游戏II Rust版本
This commit is contained in:
程序员Carl
2022-08-11 09:38:36 +08:00
committed by GitHub

View File

@ -305,6 +305,56 @@ object Solution {
}
```
### Rust
```Rust
//版本一
impl Solution {
fn max(a: i32, b:i32) -> i32 {
if a > b { a } else { b }
}
pub fn jump(nums: Vec<i32>) -> i32 {
if nums.len() == 0 { return 0; }
let mut cur_distance: i32 = 0;
let mut ans: i32 = 0;
let mut next_distance: i32 = 0;
for i in 0..nums.len() {
next_distance = Self::max(nums[i] + i as i32, next_distance);
if i as i32 == cur_distance {
if cur_distance != (nums.len() - 1) as i32 {
ans += 1;
cur_distance = next_distance;
if next_distance == (nums.len() - 1) as i32 { break; }
}
else { break; }
}
}
ans
}
}
```
```Rust
//版本二
impl Solution {
fn max(a: i32, b:i32) -> i32 {
if a > b { a } else { b }
}
pub fn jump(nums: Vec<i32>) -> i32 {
let mut cur_distance: i32 = 0;
let mut ans: i32 = 0;
let mut next_distance: i32 = 0;
for i in 0..nums.len() - 1 {
next_distance = Self::max(nums[i] + i as i32, next_distance);
if i as i32 == cur_distance {
cur_distance = next_distance;
ans += 1;
}
}
ans
}
}
```
-----------------------