zoukankan      html  css  js  c++  java
  • LeeCode 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.)

    题目大意很明显不说了;
    对于当前位置i,它可以到达的地方是i+1, i+2,i+3, ..., i+val[i], 这些地方。

    那么每次只需要从val[i]个数中查找j+val[j]和最大的那个数字(这样写一步走的最远)。

    从这个区间查找的过程可以用线段树来维护O(log(n))的复杂度。
    代码如下:

    struct node
    {
        int l, r;
        int mx, x;
    };
    
    void build(vector<node>&arr, vector<int>&nums, int l, int r, int x)
    {
        arr[x].l = l, arr[x].r = r;
        if(l == r)
        {
            arr[x].mx = nums[l] + l, arr[x].x = l;
            return ;
        }
        int mid = (l + r) >> 1;
        build(arr, nums, l, mid, x << 1);
        build(arr, nums, mid+1, r, x << 1 | 1);
    
        if(arr[x<<1].mx > arr[x<<1|1].mx)
            arr[x].mx = arr[x<<1].mx, arr[x].x = arr[x<<1].x;
        else
            arr[x].mx = arr[x<<1|1].mx, arr[x].x = arr[x<<1|1].x;
    }
    
    pair<int, int> query(vector<node>&arr, vector<int>&nums, int l, int r, int x)
    {
        if(arr[x].l >= l && arr[x].r <= r)
            return pair<int,int> {arr[x].mx, arr[x].x};
        pair<int, int> a, b;
        if(l <= arr[x<<1].r)
            a = query(arr, nums, l, r, x<<1);
        if(r >= arr[x<<1|1].l)
            b = query(arr, nums, l, r, x<<1|1);
        if(a.first > b.first)
            return a;
        else
            return b;
    }
    
    class Solution
    {
    public:
        int jump(vector<int>& nums)
        {
            int s = nums.size();
            if(s == 1)
                return 0;
    
            vector<node> arr(s << 2);
            build(arr, nums, 0, s-1, 1);
            int b = 0, ans = 0;
            while(b < s)
            {
                if(b == s-1)
                    break;
    
                if(b+nums[b] >= s-1)
                {
                    ans ++;
                    break;
                }
    
                ans ++;
    
                pair<int, int> t = query(arr, nums, b+1, b+nums[b], 1);
                b = t.second;
            }
            return ans;
        }
    };
    
  • 相关阅读:
    Windows自带Android模拟器启动失败
    Xamarin.Android提示找不到mono.Android.Support.v4
    Xamarin提示Build-tools版本过老
    Xamarin Android布局文件没有智能提示
    Xamarin.iOS模拟器调试找不到资源文件
    彻底卸载 RAD Studio 2009/2010/XE+ 的步骤
    Delphi版本号对照
    RAD Studio 2010 环境设置(转)
    C语言写的俄罗斯方块
    字符编解码的故事–ASCII,ANSI,Unicode,Utf-8区别
  • 原文地址:https://www.cnblogs.com/aiterator/p/6651934.html
Copyright © 2011-2022 走看看