Skip to content

Commit 723383e

Browse files
committed
leetcode
1 parent 2731348 commit 723383e

File tree

4 files changed

+82
-0
lines changed

4 files changed

+82
-0
lines changed

JumpGameII/jump_game_ii.dart

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
3+
4+
-* 45. Jump Game II *-
5+
6+
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
7+
8+
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
9+
10+
0 <= j <= nums[i] and
11+
i + j < n
12+
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
13+
14+
15+
16+
Example 1:
17+
18+
Input: nums = [2,3,1,1,4]
19+
Output: 2
20+
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
21+
Example 2:
22+
23+
Input: nums = [2,3,0,1,4]
24+
Output: 2
25+
26+
27+
Constraints:
28+
29+
1 <= nums.length <= 104
30+
0 <= nums[i] <= 1000
31+
32+
33+
*/
34+
35+
import 'dart:math';
36+
37+
class A {
38+
int jump(List<int> nums) {
39+
int ans = 0;
40+
int size = nums.length;
41+
int currentEnd = 0;
42+
int currentFarthest = 0;
43+
44+
for (int i = 0; i < size - 1; i++) {
45+
currentFarthest = max(currentFarthest, i + nums[i]);
46+
if (i == currentEnd) {
47+
ans++;
48+
currentEnd = currentFarthest;
49+
}
50+
}
51+
return ans;
52+
}
53+
}

JumpGameII/jump_game_ii.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package main
2+
3+
func jump(nums []int) int {
4+
if len(nums) == 1 {
5+
return 0
6+
}
7+
var maximum int = 0
8+
var current int = 0
9+
var count int = 0
10+
for i := 0; i < len(nums)-1; i++ {
11+
maximum = max(maximum, i+nums[i])
12+
if current == i {
13+
current = maximum
14+
count++
15+
}
16+
if current > len(nums)-1 {
17+
return count
18+
}
19+
}
20+
return count
21+
}
22+
23+
func max(a int, b int) int {
24+
if a > b {
25+
return a
26+
}
27+
return b
28+
}

JumpGameII/jump_game_ii.md

Whitespace-only changes.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ This repo contain leetcode solution using DART and GO programming language. Most
205205
- [**6.** Zigzag Conversion](ZigzagConversion/zigzag_conversion.dart)
206206
- [**1470.** Shuffle the Array](ShuffleTheArray/shuffle_the_array.dart)
207207
- [**904.** Fruit Into Baskets](FruitIntoBaskets/fruit_into_baskets.dart)
208+
- [**45.** Jump Game II](JumpGameII/jump_game_ii.dart)
208209

209210
## Reach me via
210211

0 commit comments

Comments
 (0)