Jump Game

来源:互联网 发布:java反序列化漏洞 编辑:程序博客网 时间:2024/06/05 09:17

JumpGame 1

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.
Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

这题比较简单,给你一个数组,里面的每个元素表示你可以向后跳跃的步数,我们需要知道能不能移动到最后一个元素。
采用贪心法即可,每次跳一步,看剩余步数和能补充的步数即num[i]哪个大,剩余步数就等于哪个,如果当可跳跃次数小于0 还没到达 ,那么失败!

类似于加油问题,能补充进来比当前大,那就补充! 贪心

        if (nums.length == 0)            return true;        int step = nums[0];        for (int i = 1; i <nums.length; i ++)        {            step --;            //每走一步,步数减1            if (step < 0)                return false;            //可补充数大于剩余步数            if (nums[i] > step)                step = nums[i];        }        return true;    }

Jump Game2

jump2 需要我们求出最少的步数

    /*    这题不同于上题,只要求我们得到最少的跳跃次数,所以铁定能走到终点的,这里仍然使用贪心法。    维护两个变量,当前能达到的最远点p以及下一次能达到的最远点q,在p的范围内迭代计算q,然后更新步数,并将最大的q设置为p,重复这个过程知道p达到终点     */    public static int jump(int[] nums) {        int cur=0,step=0,next=0;        int i = 0;        while (i < nums.length)        {            if (next >= nums.length -1)                break;            while (i <= cur)            {                next = Math.max(next,nums[i]+i);                i++;            }            step++;            cur = next;        }        return step;    }
0 0
原创粉丝点击