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;
}
};