zoukankan      html  css  js  c++  java
  • Jump Game

    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.

    思路:

      贪心算法,每一步都看能达到的最大地点

    我的代码:

    public class Solution {
        public boolean canJump(int[] A) {
            if(A == null || A.length <= 1)    return true;
            int left = 0;
            int right = 0;
            int max = 0;
            int len = A.length;
            while(left <= right)
            {
                max = Math.max(left+A[left],max);
                if(left == right)
                {
                    if(max >= len - 1) return true;
                    if(max <= right)    return false;
                    left = right + 1;
                    right = max;
                }
                else
                    left++;
            }
            return false;
        }
        
    }
    View Code

    他人代码:

        public boolean canJump(int[] A) {
            if (A == null) {
                return false;
            }
            int len = A.length;
            int right = 0;        
            for (int i = 0; i < A.length; i++) {
                right = Math.max(right, i + A[i]);
                if (right == len - 1) {
                    return true;
                }
                if (i == right) {
                    return false;
                }
            }
            return true;
        }
    View Code

    学习之处:

    • 每一步都维护一个能到达的最右侧的位置
  • 相关阅读:
    解题:POI 2006 Periods of Words
    解题:NOI 2014 动物园
    1483. 最高平均分
    1438. 较大分组的位置(回顾)
    1258. 漂亮子数组
    1903. 部门统计(回顾)
    1509. 柠檬水找零
    1451. 到最近的人的最大距离
    1425. 比较含退格的字符串
    1394. 山羊拉丁文
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4337496.html
Copyright © 2011-2022 走看看