55. 跳跃游戏
代码
javascript
// 55. 跳跃游戏:https://leetcode.cn/problems/jump-game/description/
// 输入:nums = [2,3,1,1,4]
// 输出:true
export function jumpGame (nums) {
let position = 0
let len = nums.length
for (let i = 0; i < len; i++) {
if (i <= position) {
position = Math.max(position, i + nums[i])
if (position >= len - 1) {
return true
}
}
}
return false
}
typescript
// 55. 跳跃游戏:https://leetcode.cn/problems/jump-game/description/
// 输入:nums = [2,3,1,1,4]
// 输出:true
export function jumpGame (nums: number[]): boolean {
let position = 0
let len = nums.length
for (let i = 0; i < len; i++) {
if (i <= position) {
position = Math.max(position, i + nums[i])
if (position >= len - 1) {
return true
}
}
}
return false
}
测试代码
ts
import { expect, test } from 'vitest'
import { jumpGame } from './typescript.ts'
import { jumpGame as jumpGameJs } from './javascript.js'
test(`jumpGame`, () => {
expect(jumpGame([2,3,1,1,4])).toBe(true)
expect(jumpGame([3,2,1,0,4])).toBe(false)
})
test(`jumpGameJs`, () => {
expect(jumpGameJs([2,3,1,1,4])).toBe(true)
expect(jumpGameJs([3,2,1,0,4])).toBe(false)
})