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 贪心算法:方法一