zoukankan      html  css  js  c++  java
  • 【Leetcode】经典的Jump Game in JAVA

    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.

    这道题的巧妙之处在于,每个值能够跳“值”大小步数。所以我们的思路例如以下:

    1.记录到如今为止能跳到最远的距离,记为max

    2.每个点能走的步数,记为step,且每往前面走一步。step--

    3.推断到这个点后往后跳的步数是不是大于max,假设是就更新max,不是就继续往前走

    这种话我们能够看到:假设前面这个点是零,且这个时候step步数不够你迈过去,那么就会自己主动跳出返回false。

    可是假设能够一直这么走走到终点,那么返回true

    package testAndfun;
    
    public class jumpGame {
    	public static void main(String args[]){
    		int[] A = {3,0,0,0};
    		jumpGame jp = new jumpGame();
    		if(jp.canJump(A))	System.out.println("We win");
    		else System.out.println("we lose");
    	}
    	
        public boolean canJump(int[] A) {
        	int max = 0;
        	int step = 1;
        	if(A.length<=1)	return true;
        	if(A[0]==0&&A.length>1) return false;
        	for(int i=0;i<A.length;i++){
        	   
        	    step--;
        		if(i+A[i]>max){
        			max = i+A[i];
        			step = A[i];
        		}
        		if(step==0 && i<A.length-1)	return false;
    
        	}
        	return true;
    }
        }


  • 相关阅读:
    法正(17):玄德
    法正(16):舌战
    法正(15):卢氏
    法正(14):寿星
    struts2笔记---struts2的执行过程
    Oracle数据库(一)
    flask的使用(一)
    struts2--笔记(一)
    docker基础(二)
    docker安装及问题处理
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6803761.html
Copyright © 2011-2022 走看看