GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/solution/0000-0099/0055.Jump Game/README.md at main · bobbie-zou/leetcode

Expand file tree

/

README.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
149 lines (114 loc) · 2.79 KB
/

README.md

Copy path

File metadata and controls

149 lines (114 loc) · 2.79 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

55. 跳跃游戏

English Version

题目描述

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标。

 

示例 1:

输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。

示例 2:

输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。

 

提示:

  • 1 <= nums.length <= 3 * 104
  • 0 <= nums[i] <= 105

解法

贪心。

Python3

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        mx = 0
        for i, num in enumerate(nums):
            if i > mx:
                return False
            mx = max(mx, i + num)
        return True

Java

class Solution {
    public boolean canJump(int[] nums) {
        int mx = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (i > mx) {
                return false;
            }
            mx = Math.max(mx, i + nums[i]);
        }
        return true;
    }
}

C++

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

Go

func canJump(nums []int) bool {
	mx := 0
	for i, num := range nums {
		if i > mx {
			return false
		}
		mx = max(mx, i+num)
	}
	return true
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

C#

public class Solution {
    public bool CanJump(int[] nums) {
        int mx = 0;
        for (int i = 0; i < nums.Length; ++i)
        {
            if (i > mx)
            {
                return false;
            }
            mx = Math.Max(mx, i + nums[i]);
        }
        return true;
    }
}

...


You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.