Greedy

来源:互联网 发布:mac窗口关闭快捷键 编辑:程序博客网 时间:2024/05/22 08:18

45. Jump Game II


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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

求到达最后元素的最少步数。用贪心法求解,从nums[0]开始遍历,设从当前位置i所能到达的最远距离为coverPos,那么从i+1到coverPos进行遍历,寻找从该范围内的位置出发所能到达的最远距离,记录能到达最远距离的出发点j为当前所走一步的终点。再次遍历时,从j开始,遍历j+1到新的coverPos之间的位置,以此类推直到coverPos能覆盖最后一个元素为止。

class Solution {public:    int jump(vector<int>& nums) {        int n=nums.size();        if(n<=1) return 0;        int steps=0;        int coverPos=0;        for(int i=0;i<n;){            if(nums[i]==0) return -1;            coverPos=nums[i]+i;            steps++;            if(coverPos>=n-1){                return steps;            }            int maxDistance=0;            for(int j=i+1;j<=coverPos;j++){                if(nums[j]+j>maxDistance){                    maxDistance=nums[j]+j;                    i=j;                }            }        }        return steps;    }};

55. 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.

For example:
A = [2,3,1,1,4], return true.

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

与上一题基本相同,只要判断能否到达最后的元素。依然是贪心的思路,每次把当前位置出发所能到达的最远位置存储在cover中,每次循环时判断当前位置是否在cover的范围内,一旦当前位置超出cover,则返回false。当cover达到最后元素时返回true。

class Solution {public:    bool canJump(vector<int>& nums) {        int n=nums.size();        if(n<=0) return false;        int cover=0;        for(int i=0;i<=cover && i<n;i++){            if(cover<nums[i]+i){                cover=nums[i]+i;            }            if(cover>=n-1){                return true;            }        }        return false;    }};



0 0
原创粉丝点击