55. Jump Game

/**
 * 55. Jump Game
 * https://leetcode.com/problems/jump-game/description/
 * */
class Solution {
    fun canJump(nums: IntArray): Boolean {
        //method 1
        /*var lastGoodIndexPostion = nums.size - 1
        for (i in nums.size - 1 downTo 0) {
            //i+nums[i] represent the maximum distance that current i can reach
            if (i + nums[i] >= lastGoodIndexPostion) {
                lastGoodIndexPostion = i
            }
        }
        return lastGoodIndexPostion == 0*/

        //method 2
        var max = 0
        for (i in 0 until nums.size) {
            if (i > max) {
                return false
            }
            max = Math.max(max, i + nums[i])
        }
        return true
    }
}

 

posted @ 2020-03-25 12:39  johnny_zhao  阅读(101)  评论(0编辑  收藏  举报