File tree Expand file tree Collapse file tree 2 files changed +30
-17
lines changed Expand file tree Collapse file tree 2 files changed +30
-17
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int jump (vector<int >& nums) {
4+ int len = nums.size ();
5+
6+ int ret = 0 ;// 当前跳数
7+ int last = 0 ;// 上一跳可达最远距离
8+ int curr = 0 ;// 当前一跳可达最远距
9+
10+ for (int i = 0 ; i < len; ++i) {
11+ // 无法向前继跳直接返回
12+ // if(i > curr){
13+ // return -1;
14+ // }
15+ // 需要进行下次跳跃,则更新last和当执行的跳数ret
16+ if (i > last) {
17+ last = curr;
18+ ++ret;
19+ }
20+ // 记录当前可达的最远点
21+ curr = max (curr, i + nums[i]);
22+ }
23+
24+ return ret;
25+ }
26+ };
Original file line number Diff line number Diff line change 11class Solution {
22public:
33 bool canJump (vector<int >& nums) {
4- int step = nums[0 ];
54 int len = nums.size ();
6-
7- for (int i = 0 ; i < len; i++)
8- {
9- if (step-- <= 0 )
10- return false ;
11-
12- if (step < nums[i])
13- {
14- step = nums[i];
15- }
16-
17- if (i + 1 + step >= len)
18- {
19- return true ;
20- }
5+ int reach = 0 ;
6+ for (int i = 0 ; i <= reach && i < len; ++i) {
7+ reach = max (reach, i + nums[i]);
218 }
22- return false ;
9+ return reach >= len - 1 ;
2310 }
2411};
You can’t perform that action at this time.
0 commit comments