LeetCode 45 Jump Game II

topic

This question is at first glance, I thought it was dynamic programming. LeetCode but never to the data range. , But also the hard difficulty of the subject, so I guess the array length of at least 100,000 bar.

Then look closely, we found that the number of steps each step of the walk is not fixed, it can be greedy. Every take the time to jump all that nums [i] + maximum value of that point i.

The question then becomes one of seeking the maximum fast interval. Segment tree too cumbersome, or use it Fenwick tree, easy to understand.

c++

class Solution {
public:
    int c[100005];
    int d[100005];
    int a[100005];
    int jump(vector<int>& nums) {
        
        if(nums.size()<=1)
            return 0;
        for(int i=0;i<nums.size();i++)
        {
            a[i]=nums[i]+i;
            Add(i+1,a[i],nums.size());
        }
        
        int start =0;
        int ans=0;
        while(start<nums.size())
        {
            if(nums[start]+start>=nums.size()-1)
            {
                ans++;
                break;
            }
            int m = Max(start+1,nums[start]+start+1);
            ans++;
           
            start = m;
        }
        return ans;
           
    }
    
    int lowbit(int x)
    {
        return x&(-x);
    }

    void Add(int x,int y,int n)
    {
        int pos=x-1;
        if(c[x]<y)
        {
         c[x]=y;
         d[x]=pos;
        }
     x+=lowbit(x);
    while(x<=n)
    {
        if(c[x]<y)
        {
            c[x]=y;
            d[x]=pos;
        }
        x+=lowbit(x);
    }
}

int Max(int l,int r)
{
    int ans=-999999;
    int res=r-1;
    while(r>l)
    {
        if(ans<a[r-1])
        {
            ans=a[r-1];
            res=r-1;
        }
        if(r-lowbit(r)>=l)
        {
            if(ans<c[r])
            {
                ans=c[r];
                res=d[r];
            }
            r-=lowbit(r);
        }
        else
        {
            r--;
        }
    }
    return res;
}


};

Guess you like

Origin www.cnblogs.com/dacc123/p/11373526.html