From b806ec7959f2b4de0df46d514de2caf0e39ac22e Mon Sep 17 00:00:00 2001 From: yige Date: Mon, 4 May 2020 13:43:56 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8F=20I?= =?UTF-8?q?I?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/array/jump-game-ii.js | 20 ++++++++++++++++++++ test/array/jump-game-ii.test.js | 5 +++++ 3 files changed, 30 insertions(+) create mode 100644 src/array/jump-game-ii.js create mode 100644 test/array/jump-game-ii.test.js diff --git a/README.md b/README.md index f5d1616..a0036ef 100644 --- a/README.md +++ b/README.md @@ -235,6 +235,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 面试题42. 连续子数组的最大和 https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/ - LintCode 41. 最大子数组 https://www.lintcode.com/problem/maximum-subarray/description +- [跳跃游戏II](src/array/jump-game-ii.js) + + - LeetCode 45. 跳跃游戏 II https://leetcode-cn.com/problems/jump-game-ii/ + - LintCode 117. 跳跃游戏 II https://www.lintcode.com/problem/jump-game-ii/description + ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) diff --git a/src/array/jump-game-ii.js b/src/array/jump-game-ii.js new file mode 100644 index 0000000..ce9cf76 --- /dev/null +++ b/src/array/jump-game-ii.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @return {number} + */ +export const jump = function (nums) { + let step = 0 // 跳跃步数 + let maxPosition = 0 // 最大位置 + let lastJumpStepMax = 0 // 最后一次跳跃最大能跳的步数 + + for (let n = 0, len = nums.length; n < len - 1; n++) { + maxPosition = Math.max(maxPosition, nums[n] + n) + if (lastJumpStepMax === n) { // 从当前位置开始,到当前能跳的位置这个区间,谁最大,就选谁,并跳一次 + lastJumpStepMax = maxPosition + step++ + } + if (lastJumpStepMax > len) return step + } + + return step +} diff --git a/test/array/jump-game-ii.test.js b/test/array/jump-game-ii.test.js new file mode 100644 index 0000000..8d44d96 --- /dev/null +++ b/test/array/jump-game-ii.test.js @@ -0,0 +1,5 @@ +import { jump } from '../../src/array/jump-game-ii' + +test('跳跃游戏II', () => { + expect(jump([2, 3, 1, 1, 4])).toBe(2) +})