You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution {
public:intjump(vector<int>& nums) {
int n = nums.size();
int ans = 0, i = 0; // i 是当前所在位置while (i < n - 1) {
int maxL = i, len = i + nums[i];
if (i + nums[i] >= n - 1) return ans + 1; // 若当前位置可以调到最终位置直接返回for (int j = i + 1; j < n && j <= len; j++) { // 寻找能调到范围中跳的最远的一个位置int to = j + nums[j];
if (maxL <= to) {
maxL = to;
i = j;
}
}
ans++;
}
return ans;
}
};
The text was updated successfully, but these errors were encountered:
题目描述
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
样例
假设你总是可以到达数组的最后一个位置。
算法
(贪心)
时间:O(n) & 空间:O(1)
C++ 代码
The text was updated successfully, but these errors were encountered: