LeetCode 45. Jump Game II|贪心算法

来源:互联网 发布:怎么开通淘宝直播间 编辑:程序博客网 时间:2024/06/05 16:47

题目描述

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.

算法分析

这道题是困难的难度,但实际上也不太难,这道题有很多种解法,我的解法效率虽然不算很高,但是使用了单纯的贪心算法,容易理解,而且还可以把路径保存起来。
我这个算法在于,每一次选择下一个点时,会判断选择该点之后,是不是能够跳的更加远,这就需要有一个内部的循环进行判断。判断在目前位置到可到达的位置之间,选择一个能够让我下一步跳的更远的点。思想十分简单,但因为有内部循环,所以效率会比起加入动态规划算法慢了许多,不过也可以通过。时间复杂度最好的是O(N),最差的不会超过O(N^2)。

int jump(vector<int>& nums) {    if(nums.size()<2) return 0;    int i = 0;    int count = 0;    while(i<nums.size()-1){        count++;                if(i+nums[i]>=nums.size()-1) return count;        int  j = 1;        int best = 0;        int max_jump= 0;         for( ; j <= nums[i] ; j++){            if(nums[i+j]+j>max_jump){                max_jump = nums[i+j]+j;                 best = j;            }        }        i+=best;     }    return count;}
0 0