LeetCode45. Jump Game II

来源:互联网 发布:成都盘古网络工作待遇 编辑:程序博客网 时间:2024/05/16 00:25

题目:

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

Note:
You can assume that you can always reach the last index.

题意:

从起点跳跃,每次跳跃的最大步数为该位置的数组值,求最后跳到最后一个位置上所需的最少步数。

思路:

每次跳跃都选择跳最远,如果开始跳的位置超出之前得到的最大跳跃范围preSelect,步数加1。同时preSelect更新为当前得到的最大跳跃范围。

代码:

class Solution {public:    int jump(vector<int>& nums) {        int len=nums.size();        int dis=0;        int cnt=0;        int preSelect=0;        for(int i=0;i<len;i++){            if(i>preSelect){                cnt++;                preSelect=dis;            }            dis=max(dis,nums[i]+i);        }        return cnt;    }};
0 0
原创粉丝点击