1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int jump(vector<int>& nums) { int level = 0; int maxReach = 0; int i = 0; while(maxReach < nums.size() - 1) { ++level; for(int maxT = maxReach; i <= maxT; ++i) { maxReach = max(maxReach, nums[i] + i); if(maxReach >= nums.size() - 1) return level; } } return level; } };
|
视为BFS问题
每个区域里都可以走到下一层的任何一个点,实在走不到了,只能换层了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: int jump(vector<int>& nums) { int level = 0, maxReachFurther = 0, maxReachEnd = 0; for(int i = 0; i < nums.size() - 1; ++i) { maxReachFurther = max(maxReachFurther, nums[i] + i); if(maxReachEnd == i) { maxReachEnd = maxReachFurther; ++level; } } return level; } };
|
review
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int jump(vector<int>& nums) { int level = 0; int this_level_border = 0; int cur_reach = 0; int n = nums.size(); for(int i = 0; i < n; ++i) { if(this_level_border >= n - 1) return level; cur_reach = max(cur_reach, nums[i] + i); if(this_level_border == i) { ++level; this_level_border = cur_reach; } } return level; } };
|