From 2b73437e7283230b340d72fe208b2c39c9d6a3c7 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Tue, 14 Mar 2023 11:35:23 +0800 Subject: [PATCH] =?UTF-8?q?Update=200045.=E8=B7=B3=E8=B7=83=E6=B8=B8?= =?UTF-8?q?=E6=88=8FII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 48 ++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 22151fdc..911834e1 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -379,43 +379,46 @@ object Solution { ```Rust //版本一 impl Solution { - fn max(a: i32, b:i32) -> i32 { - if a > b { a } else { b } - } pub fn jump(nums: Vec) -> i32 { - if nums.len() == 0 { return 0; } - let mut cur_distance: i32 = 0; - let mut ans: i32 = 0; - let mut next_distance: i32 = 0; - for i in 0..nums.len() { - next_distance = Self::max(nums[i] + i as i32, next_distance); - if i as i32 == cur_distance { - if cur_distance != (nums.len() - 1) as i32 { + if nums.len() == 1 { + return 0; + } + let mut cur_distance = 0; + let mut ans = 0; + let mut next_distance = 0; + for (n, &i) in nums.iter().enumerate() { + next_distance = (n as i32 + i).max(next_distance); + if i == cur_distance { + if cur_distance < n as i32 - 1 { ans += 1; cur_distance = next_distance; - if next_distance == (nums.len() - 1) as i32 { break; } + if next_distance >= n as i32 - 1 { + break; + }; + } else { + break; } - else { break; } } } ans } } + ``` ```Rust //版本二 impl Solution { - fn max(a: i32, b:i32) -> i32 { - if a > b { a } else { b } - } pub fn jump(nums: Vec) -> i32 { - let mut cur_distance: i32 = 0; - let mut ans: i32 = 0; - let mut next_distance: i32 = 0; - for i in 0..nums.len() - 1 { - next_distance = Self::max(nums[i] + i as i32, next_distance); - if i as i32 == cur_distance { + if nums.len() == 1 { + return 0; + } + let mut cur_distance = 0; + let mut ans = 0; + let mut next_distance = 0; + for (n, &i) in nums.iter().enumerate() { + next_distance = (n as i32 + i).max(next_distance); + if i == cur_distance { cur_distance = next_distance; ans += 1; } @@ -423,6 +426,7 @@ impl Solution { ans } } + ```