classSolution { public: intjump(vector<int>& nums){ //贪心 int n=nums.size(); int end=0; //标记可以选择的跳跃步数的最后一个 int farthest=0; //所有可选择跳跃步数[i...end]中能够跳到的最远距离 int res=0; //记录跳跃次数 for(int i=0;i<n-1;i++){ // 更新能跳到的最远距离 farthest = max(farthest, i+nums[i]); if(end==i){ res++; end = farthest; } } return res; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcjump(nums []int)int { //贪心 n := len(nums) end := 0//标记可以选择的跳跃步数的最后一个 farthest := 0//所有可选择跳跃步数[i...end]中能够跳到的最远距离 res := 0//记录跳跃次数 for i := 0; i < n-1; i++ { // 更新能跳到的最远距离 if i+nums[i] > farthest { farthest = i + nums[i] } if end == i { res++ end = farthest } } return res }