zoukankan      html  css  js  c++  java
  • lintcode-117-跳跃游戏 II

    117-跳跃游戏 II

    给出一个非负整数数组,你最初定位在数组的第一个位置。
    数组中的每个元素代表你在那个位置可以跳跃的最大长度。   
    你的目标是使用最少的跳跃次数到达数组的最后一个位置。

    样例

    给出数组A = [2,3,1,1,4],最少到达数组最后一个位置的跳跃次数是2(从数组下标0跳一步到数组下标1,然后跳3步到数组的最后一个位置,一共跳跃2次)

    标签

    贪心 数组

    思路

    使用贪心算法,用2个变量 end, farthest 分别从当前(第 i 位)到第 end 位,可以一次跳跃的最远距离farthest ,当移动到第 end 位时,再次跳跃,直至跳出

    code

    class Solution {
    public:
        /**
         * @param A: A list of lists of integers
         * @return: An integer
         */
        int jump(vector<int> A) {
            // wirte your code here
            int size = A.size();
            if(size <= 0){
                return 0;
            }
            
            int farthest = 0, end = 0, minJump = 0;
            for(int i=0; i<size; i++) {
                farthest = (farthest > A[i]+i) ? farthest : A[i]+i;
                if(i == end && end < size-1) {
                    minJump++;
                    end = farthest;
                }
            }
    
            return minJump;
        }
    };
    
  • 相关阅读:
    python自定义线程池
    sudo: ulimit: command not found
    HTTP长连接、短连接使用及测试
    5分钟上手:本地开发环境启动HTTPS
    Python复杂对象转JSON
    Python自定义注解
    gcc makefile
    Ubuntu 13.10 安装 ia32-lib
    vim扩展配置
    python异常类型
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7205896.html
Copyright © 2011-2022 走看看