leetcode 45.Jump GameII

来源:互联网 发布:淘宝手机端买家秀 编辑:程序博客网 时间:2024/06/08 15:16

题目描述:
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.)

分析:此题没有考虑无法到达终点的情况。思路是分别比较直接从该位置跳跃出最大步数和跳跃一步到下一个位置从该位置继续跳跃哪一个跳跃长度长,贪最长的。

AC代码(来自九章算法Java版)

public class Solution {    public int jump(int[] nums) {        if(nums==null||nums.length==0) return 0;        int start=0,end=0,jumps=0;        while(end<nums.length-1){            jumps++;            int len=end;            for(int i=start;i<=end;i++){                if(nums[i]+i>len){                    len=nums[i]+i;                }            }            start=end+1;            end=len;        }        return jumps;    }}

可以变形一道题目,题目来自2017搜狐校招真题


[编程题] 袋鼠过河

时间限制:1秒
空间限制:32768K

一只袋鼠要从河这边跳到河对岸,河很宽,但是河中间打了很多桩子,每隔一米就有一个,每个桩子上都有一个弹簧,袋鼠跳到弹簧上就可以跳的更远。每个弹簧力量不同,用一个数字代表它的力量,如果弹簧力量为5,就代表袋鼠下一跳最多能够跳5米,如果为0,就会陷进去无法继续跳跃。河流一共N米宽,袋鼠初始位置就在第一个弹簧上面,要跳到最后一个弹簧之后就算过河了,给定每个弹簧的力量,求袋鼠最少需要多少跳能够到达对岸。如果无法到达输出-1

输入描述:
输入分两行,第一行是数组长度N (1 ≤ N ≤ 10000),第二行是每一项的值,用空格分隔。

输出描述:
输出最少的跳数,无法到达输出-1

输入例子1:
5
2 0 1 1 1

输出例子1:
4

分析:
结题思路同Jump Game,但是要考虑未能抵达的情况,也好判断,就是当步数大于数组数说明未能抵达。

AC代码(c++版)

#include <iostream>#include <string>using namespace std;int jump(int nums[], int n) {    if (n == 0) return 0;    int start = 0, end = 0, jumps = 0;    while (jumps<=n&&end<=n - 1){        ++jumps;        int len = end;        for (int i = start; i <= end; i++){            if (nums[i] + i>len){                len = nums[i] + i;            }        }        start = end + 1;        end = len;    }    if (jumps > n)        jumps = -1;    return jumps;}int main(){    int n;    cin >>n;    int *array=new int[n];    for (int i = 0; i < n; i++){        cin >> array[i];    }    cout << jump(array, n);    return 0;}
原创粉丝点击