zoukankan      html  css  js  c++  java
  • jump game

    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.

    。。数组中的数字表示最多可以跳几步。贪心的题,,用“局部最优和全局最优解法”。我们维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。局部最优(当前出发能跳到的最远距离)local=A[i]+i,而全局最优则是global=Math.max(global, local)。只要最远距离能到最后一个位置就行。

    class Solution {
        public boolean canJump(int[] nums) {
            /*题目说:数组中的每个数字代表当前位置最多可以跳几步。*/
            if(nums==null||nums.length==0) return false;
            int reach=0;//能跳到的最远距离
            //当前位置如果大于最远距离,跳出循环,因为前面都跳不到这里。
            for(int i=0;i<nums.length-1&&i<=reach;i++){
                reach=Math.max(nums[i]+i,reach);
            }
            if(reach<nums.length-1) return false;
            
            return true;
        }
    }

     还有反向的思维:从倒数第二个元素往前看,该位置开始跳,能否跳过最后一个元素,如果不能,则看前面一个位置;如果可以,则只要考虑前面位置能否跳到该位置。

    public class Solution {  
        public boolean canJump(int[] A) {  
            int last = A.length - 1;  
            for (int i = A.length - 2; i >= 0; i--) {  
                if (i + A[i] >= last) {  
                    last = i;  
                }  
            }  
            return (last <= 0);  
        }  
    }  

    自己的做法:自己想着,跳不到最后都是因为跳0步导致的。从后往前找0,然后看前面的元素能否跳过这个0,也就是前面元素是否大于该元素到0的 距离。如果跳不过,则要返回false。。

     for(int i=nums.length-2;i>=0;i--){
                if(nums[i]==0){
                    int index=0;
                    
                    while((--i)>=0&&nums[i]<=(++index)){}
                    if(i<0) return false;
                    
                }
            }
    
    return true;
  • 相关阅读:
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
    团队作业-随堂小测(同学录)
    Alpha 冲刺 (5/10)
    LeetCode-1
    c++向量
    软件工程实践总结作业
    个人作业——软件产品案例分析
    个人技术博客Alpha----Android Studio学习
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8195508.html
Copyright © 2011-2022 走看看