算法分析与设计week04--55.Jump Game

来源:互联网 发布:好用的洗面奶知乎 编辑:程序博客网 时间:2024/06/07 01:06

55.Jump Game

Description

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.

Example

A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

Analyse

题意:
给出一个非负数组,初始位置为数组的第一个位置,数组中的元素表示你能跳的最远距离。问是否可以到达最后一个索引位置。

贪心算法:
第一步:从第一个位置开始,计算从该位置出发所能到达的最远距离,然后和sums.length - 1作比较:
“局部最优和全局最优解法”:维护一个到目前为止能跳到的最远距离,以及从当前一步出发能跳到的最远距离。局部最优local = sums[i] + i,而全局最优则是global = max(global, local)。

class Solution {public:    bool canJump(vector<int>& nums) {        int local = 0;        int global = 0;        for (int i = 0; i < nums.size(); i++) {            if (global < i) break;  //  任意 i 位置出现maxstep为0的情况,则说明无法继续向前移动            local = i + nums[i];            global = max(global, local);        }        return nums.size() - 1 <= global;    }};

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)

另一种贪心解法:逆向考虑

(官网参考答案:https://leetcode.com/problems/jump-game/solution/)
From a given position, when we try to see if we can jump to a GOOD position, we only ever use one - the first one (see the break statement). In other words, the left-most one. If we keep track of this left-most GOOD position as a separate variable, we can avoid searching for it in the array.

class Solution {public:    bool canJump(vector<int>& nums) {        int lastPos = nums.size() - 1;        for (int i = lastPos; i >= 0; i--) {            if (i + nums[i] >= lastPos) {                lastPos = i;            }        }        return lastPos == 0;    }};
原创粉丝点击