C++ Solution for Jump Game

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int k = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (i > k) return false;
            k = max(k, i + nums[i]);
        }
        return true;
    }
};

Dart Solution for Jump Game

class Solution {
  bool canJump(List<int> nums) {
    int k = 0;
    for (int i = 0; i < nums.length; i++) {
      if (i > k) return false;
      k = max(k, i + nums[i]);
    }
    return true;
  }
}

Explanation:

The solution employs a greedy approach. It iterates through the array nums, maintaining a variable k representing the farthest reachable index. At each step, it checks if the current index i is greater than k. If it is, it means the current index cannot be reached, and the function returns false. Otherwise, it updates k to the maximum of its current value and the farthest reachable index from the current position (i + nums[i]).

If the loop completes without encountering a situation where i is greater than k, it implies that the last index can be reached, and the function returns true.

C++ and Dart Solution for Jump Game Problem

原文地址: https://www.cveoy.top/t/topic/qfD7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录