-
Notifications
You must be signed in to change notification settings - Fork 21
/
JumpGame.swift
50 lines (42 loc) 路 1.11 KB
/
JumpGame.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// JumpGame.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 04/01/2018.
// Copyright 漏 2018 lizhaotailang. All rights reserved.
//
// 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.
//
// Accepted. See [JumpGameTests](./LeetCodeTests/JumpGameTests.swift) for test cases.
//
import Foundation
class JumpGame {
func canJump(_ nums: [Int]) -> Bool {
if nums.count == 0 {
return false
}
if nums.count == 1 {
return true
}
var maxLength = 0
var i = 0
while i < nums.count - 1 {
maxLength -= 1
maxLength = max(maxLength, nums[i])
if maxLength == 0 {
return false
}
i += 1
}
return maxLength > 0
}
}