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;
        }
    };
    
  • 相关阅读:
    源码0603-08-掌握-NSURLSession-上传
    源码0603-05-掌握-大文件下载
    源码0603-03-掌握-NSURLSession
    源码0603-01-了解-大文件下载(NSOutputStream)
    源码0602-10-掌握-文件上传11-了解-获得文件的MIMEType
    源码0602-08-掌握-解压缩
    源码0602-06-掌握-小文件下载-大文件下载
    用JS实现的控制页面前进、后退、停止、刷新以及加入收藏等功能
    java一路走来
    CKEditor3.5.3 JAVA下使用
  • 原文地址:https://www.cnblogs.com/aiterator/p/6651934.html
Copyright © 2011-2022 走看看