55. Jump Game
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
- new solution update 2022.02.04
1 2 3 4 5 6 7 8 9 10
| class Solution { public: bool canJump(vector<int>& nums) { int maxIdx = 0; for(int i = 0; i <= maxIdx and i < nums.size(); i++) { maxIdx = max(maxIdx, i + nums[i]); } return maxIdx >= nums.size() - 1; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: bool canJump(vector<int>& nums) { vector<bool> v(nums.size(), false); queue<int> q; v[0] = true; q.push(0); while(!q.empty() && !v.back()) { int pos = q.front(); q.pop(); for(int i = min(pos + nums[pos], (int)nums.size() - 1); i > pos; i--) { if(!v[i]) { q.push(i); v[i] = true; } } } return v.back(); } };
|