zoukankan      html  css  js  c++  java
  • JumpGame,JumpGame2

    JumpGame:给定一个非负整数数组,开始在第一个位置,每个位置上的数字代表最大可以跳跃的步数,判断能不能跳到最后一个位置。

    例如:A=[2,3,1,1,4],在位置0处,可以跳一步到位置1,位置1跳3步到位置4.

    public class JumpGame {
    	public static boolean canJump(int[] a)
    	{
    		int reach = 0;//代表最多能到达的位置
    		int i = 0; //代表每次走一步能到达的位置
    		for(; i < a.length && i <= reach; i ++)
    		{
    			reach = Math.max(reach, i + a[i]);
    		}
    		return i == a.length;
    	}
    	public static void main(String[] args) {
    		int[] a = {2,3,1,1,4};
    		System.out.println(canJump(a));
    	}
    }
    

    JumpGame2:给定一个非负整数数组,开始在第一个位置,每个位置上的数字代表最大可以跳跃的步数,求跳到最后位置需要最少的跳跃次数。

    例如:A=[2,3,1,1,4],在位置0处,可以跳一步到位置1,位置1跳3步到位置4.最少次数是2。用一个数组记录到达每个位置的前一个位置。

    public static int canJump2(int[] a)
    	{
    		int pre[] = new int[a.length];//记录到达i的前一位置
    		int reach = 0;
    		for(int i = 0; i < a.length; i ++)
    		{
    			if(i+a[i] > reach)
    			{
    				//reach+1 - i+a[i]的前一位置是i
    				for(int j = reach + 1; j <= i + a[i] && j < a.length; j ++)
    				{
    					pre[j] = i;
    				}
    				reach = i + a[i];
    			}
    		}
    		int count = 0;
    		int k = a.length -1;
    		while(k > 0)
    		{
    			k = pre[k];
    			count ++;
    		}
    		return count;
    	}
    
  • 相关阅读:
    LeetCode Flatten Binary Tree to Linked List
    LeetCode Longest Common Prefix
    LeetCode Trapping Rain Water
    LeetCode Add Binary
    LeetCode Subsets
    LeetCode Palindrome Number
    LeetCode Count and Say
    LeetCode Valid Parentheses
    LeetCode Length of Last Word
    LeetCode Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5746696.html
Copyright © 2011-2022 走看看