zoukankan      html  css  js  c++  java
  • Jump Game II

    题目:Given an array of non-negative integers, you are initially positioned at the first index of the array.

    Each element in the array represents your maximum jump length at that position.

    Your goal is to reach the last index in the minimum number of jumps.

    For example:
    Given array A = [2,3,1,1,4]

    The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

    思路:贪心

    本题可以这样理解,last用来保存上一次step步能走的最大位置,然后,在i还在那个范围里面,我就只更新current的数值大小,current代表此前的位置再往前走能够到达的最大位置。尽管我可能还在循环里面,还在last的范围里面,但是我一直在更新current的数值,也就是说,我就是要走最大值,但是后面超过了,我其实是从那个current的那个地方走,这就是current更新的意义。

    代码:

    class Solution {
    //https://leetcode.com/problems/jump-game-ii/
    public:
        int jump(vector<int>& nums) {
            int n=nums.size();
            int max=0,sum=0,start=1;
            for(int i=0;i< n;i++){
                if(i>=start){
                    start=max+1;
                    sum++;
                }
                if(i+nums[i]>max){
                    max=i+nums[i];
                }
            }
            return sum;
        }
    };


  • 相关阅读:
    Spring事务管理
    Spring中使用Hibernate
    tkinter学习笔记_04
    tkinter学习笔记_03
    tkinter学习笔记_02
    tkinter学习笔记_01
    tkinter模块常用参数(python3)
    单选框默认选中
    Tkinter & mysql 的登录框练习
    python爬虫-喜马拉雅_晚安妈妈睡前故事
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519890.html
Copyright © 2011-2022 走看看