File tree 3 files changed +12
-60
lines changed
solution/0000-0099/0055.Jump Game
3 files changed +12
-60
lines changed Original file line number Diff line number Diff line change @@ -118,29 +118,13 @@ impl Solution {
118
118
#[allow(dead_code)]
119
119
pub fn can_jump(nums: Vec<i32>) -> bool {
120
120
let n = nums.len();
121
- let mut i: usize = 0;
121
+ let mut mx = 0;
122
122
123
- while i < n {
124
- if nums[i] as usize + i >= n - 1 {
125
- break;
126
- }
127
- let mut j: usize = 1;
128
- let mut max_step = 0;
129
- let mut next_i: usize = 0;
130
- // Get the next max step
131
- while j <= nums[i] as usize {
132
- if (i + j) as i32 + nums[i + j] >= max_step {
133
- max_step = (i + j) as i32 + nums[i + j];
134
- next_i = i + j;
135
- }
136
- j += 1;
137
- }
138
- if max_step == 0 {
139
- // No further max step
123
+ for i in 0..n {
124
+ if mx < i {
140
125
return false;
141
126
}
142
- // Otherwise, update `i` to `next_i`
143
- i = next_i;
127
+ mx = std::cmp::max(mx, i + nums[i] as usize);
144
128
}
145
129
146
130
true
Original file line number Diff line number Diff line change @@ -102,29 +102,13 @@ impl Solution {
102
102
#[allow(dead_code)]
103
103
pub fn can_jump(nums: Vec<i32>) -> bool {
104
104
let n = nums.len();
105
- let mut i: usize = 0;
105
+ let mut mx = 0;
106
106
107
- while i < n {
108
- if nums[i] as usize + i >= n - 1 {
109
- break;
110
- }
111
- let mut j: usize = 1;
112
- let mut max_step = 0;
113
- let mut next_i: usize = 0;
114
- // Get the next max step
115
- while j <= nums[i] as usize {
116
- if (i + j) as i32 + nums[i + j] >= max_step {
117
- max_step = (i + j) as i32 + nums[i + j];
118
- next_i = i + j;
119
- }
120
- j += 1;
121
- }
122
- if max_step == 0 {
123
- // No further max step
107
+ for i in 0..n {
108
+ if mx < i {
124
109
return false;
125
110
}
126
- // Otherwise, update `i` to `next_i`
127
- i = next_i;
111
+ mx = std::cmp::max(mx, i + nums[i] as usize);
128
112
}
129
113
130
114
true
Original file line number Diff line number Diff line change @@ -2,29 +2,13 @@ impl Solution {
2
2
#[ allow( dead_code) ]
3
3
pub fn can_jump ( nums : Vec < i32 > ) -> bool {
4
4
let n = nums. len ( ) ;
5
- let mut i : usize = 0 ;
5
+ let mut mx = 0 ;
6
6
7
- while i < n {
8
- if nums[ i] as usize + i >= n - 1 {
9
- break ;
10
- }
11
- let mut j: usize = 1 ;
12
- let mut max_step = 0 ;
13
- let mut next_i: usize = 0 ;
14
- // Get the next max step
15
- while j <= nums[ i] as usize {
16
- if ( i + j) as i32 + nums[ i + j] >= max_step {
17
- max_step = ( i + j) as i32 + nums[ i + j] ;
18
- next_i = i + j;
19
- }
20
- j += 1 ;
21
- }
22
- if max_step == 0 {
23
- // No further max step
7
+ for i in 0 ..n {
8
+ if mx < i {
24
9
return false ;
25
10
}
26
- // Otherwise, update `i` to `next_i`
27
- i = next_i;
11
+ mx = std:: cmp:: max ( mx, i + nums[ i] as usize ) ;
28
12
}
29
13
30
14
true
You can’t perform that action at this time.
0 commit comments