From c9621173c3ee7fb323d00125656de3dce9bcdf3c Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sat, 30 Jul 2022 14:53:49 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200134.=E5=8A=A0=E6=B2=B9?= =?UTF-8?q?=E7=AB=99=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0134.加油站 Rust版本 --- problems/0134.加油站.md | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index e5d50a9b..55064ce4 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -406,6 +406,55 @@ function canCompleteCircuit(gas: number[], cost: number[]): number { }; ``` +### Rust + +贪心算法:方法一 + +```Rust +impl Solution { + pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { + let mut cur_sum = 0; + let mut min = i32::MAX; + for i in 0..gas.len() { + let rest = gas[i] - cost[i]; + cur_sum += rest; + if cur_sum < min { min = cur_sum; } + } + if cur_sum < 0 { return -1; } + if min > 0 { return 0; } + for i in (0..gas.len()).rev() { + let rest = gas[i] - cost[i]; + min += rest; + if min >= 0 { return i as i32; } + } + -1 + } +} +``` + +贪心算法:方法二 + +```Rust +impl Solution { + pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { + let mut cur_sum = 0; + let mut total_sum = 0; + let mut start = 0; + for i in 0..gas.len() { + cur_sum += gas[i] - cost[i]; + total_sum += gas[i] - cost[i]; + if cur_sum < 0 { + start = i + 1; + cur_sum = 0; + } + } + if total_sum < 0 { return -1; } + start as i32 + } +} +``` + + ### C 贪心算法:方法一