【LeetCode】C# 55、Jump Game

来源:互联网 发布:mina发送广播数据 编辑:程序博客网 时间:2024/06/01 10:48

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

有点像飞行棋,给定数组,每个数字代表你能往前走的最大格数,判断能否到达终点。

思路:定义整数 max 来存放到达第i位时能跳到的最远的距离。当i比max大则显示失败。

public class Solution {    public bool CanJump(int[] nums) {        int max = 0;        for(int i=0;i<nums.Length;i++){            if(i>max) return false;            max = Math.Max(nums[i]+i,max);        }        return true;    }}
原创粉丝点击