zoukankan      html  css  js  c++  java
  • leetcode面试准备: Jump Game

    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.

    接口: public boolean canJump(int[] nums);

    2 思路

    从数字的0位置,开始往后挑,是否能够达到最后一个元素。

    思路1:一维动态规划

    状态F[i],表示从第0层出发,走到A[i]时剩余的还能够走的最大步数。
    F[i] < 0 :已经无法往前走了,只能够走到 i - 1层。
    方程:F[i] = max(f[i - 1], A[i - 1]) - 1, i > 0
    初始状态:F[0] = 0 或者 F[0] = A[0]
    复杂度: Time: O(n) ; Space: O(n)

    思路2:贪心思想

    maxCan表示能够走到的最远的index,不断更新这个全局最值。所以,有局部最值
    局部最值: maxLocal = A[i] + i,表示走到i层时,能够达到的最远的index。
    复杂度: Time: O(n) ; Space: O(1)

    3 代码

    思路1

    	public boolean canJump(int[] nums) {
    		int len = nums.length;
    		int[] f = new int[len];
    		f[0] = nums[0];
    		for (int i = 1; i < len; i++) {
    			f[i] = Math.max(f[i - 1], nums[i - 1]) - 1;
    			if (f[i] < 0)
    				return false;
    		}
    		return f[len - 1] >= 0 ? true : false;
    	}
    

    思路2

    	public boolean canJump2(int[] nums) {
    		int len = nums.length;
    		int maxCan = 0;
    		for (int i = 0; (i < len) && (i <= maxCan); i++) {
    			int maxLocal = nums[i] + i;
    			maxCan = maxCan > maxLocal ? maxCan : maxLocal;
    			if (maxCan >= len - 1) {
    				return true;
    			}
    		}
    		return false;
    	}
    

    4 总结

    贪心的思想,采用局部最值和全局最值,解法效率好。
    DP思想,不是很好想。
    疑问:DP的答案运行时间少于贪心的时间?

    5 扩展

    Jump Game II

    6 参考

  • 相关阅读:
    Leetcode 1002. 查找常用字符
    Leetcode 1020. 将数组分成和相等的三个部分
    Leetcode 1021. 最佳观光组合
    Leetcode 1022. 可被 K 整除的最小整数
    算法入门经典第六章 例题6-9 天平
    例题6-7 树的层次遍历
    算法入门经典第六章 例题6-4 破损的键盘
    算法入门经典-第五章 例题5-7 丑数
    算法入门经典第六章 例题6-5 移动盒子
    算法入门经典第六章 例题6-2 铁轨
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4701068.html
Copyright © 2011-2022 走看看