Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9b7cf50

Browse files
增加0045跳跃游戏的go贪心版本和python贪心版本二
1 parent f109f92 commit 9b7cf50

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

‎problems/0045.跳跃游戏II.md‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,26 @@ class Solution:
214214
return ans
215215
```
216216

217+
```python
218+
# 贪心版本二
219+
class Solution:
220+
def jump(self, nums: List[int]) -> int:
221+
if len(nums) == 1:
222+
return 0
223+
curDistance, nextDistance = 0, 0
224+
step = 0
225+
for i in range(len(nums)-1):
226+
nextDistance = max(nextDistance, nums[i]+i)
227+
if i == curDistance:
228+
curDistance = nextDistance
229+
step += 1
230+
return step
231+
```
232+
233+
234+
217235
### Go
236+
218237
```Go
219238
func jump(nums []int) int {
220239
dp := make([]int, len(nums))
@@ -240,7 +259,71 @@ func min(a, b int) int {
240259
}
241260
```
242261

262+
```go
263+
// 贪心版本一
264+
func jump(nums []int) int {
265+
n := len(nums)
266+
if n == 1 {
267+
return 0
268+
}
269+
cur, next := 0, 0
270+
step := 0
271+
for i := 0; i < n; i++ {
272+
next = max(nums[i]+i, next)
273+
if i == cur {
274+
if cur != n-1 {
275+
step++
276+
cur = next
277+
if cur >= n-1 {
278+
return step
279+
}
280+
} else {
281+
return step
282+
}
283+
}
284+
}
285+
return step
286+
}
287+
288+
func max(a, b int) int {
289+
if a > b {
290+
return a
291+
}
292+
return b
293+
}
294+
```
295+
296+
```go
297+
// 贪心版本二
298+
func jump(nums []int) int {
299+
n := len(nums)
300+
if n == 1 {
301+
return 0
302+
}
303+
cur, next := 0, 0
304+
step := 0
305+
for i := 0; i < n-1; i++ {
306+
next = max(nums[i]+i, next)
307+
if i == cur {
308+
cur = next
309+
step++
310+
}
311+
}
312+
return step
313+
}
314+
315+
func max(a, b int) int {
316+
if a > b {
317+
return a
318+
}
319+
return b
320+
}
321+
```
322+
323+
324+
243325
### Javascript
326+
244327
```Javascript
245328
var jump = function(nums) {
246329
let curIndex = 0

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /