From 65dd1924ed213bd1d2a7eb889dc9827216f454b9 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 17 Apr 2024 10:26:22 +0800 Subject: [PATCH] 20240417 Finished --- src/problem/mod.rs | 3 +- src/problem/p134_gas_station.rs | 66 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 src/problem/p134_gas_station.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index cf17ae0..4e7642e 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -103,4 +103,5 @@ mod p55_jump_game; mod p45_jump_game_ii; mod p274_h_index; mod p380_insert_delete_getrandom_o1; -mod p238_product_of_array_except_self; \ No newline at end of file +mod p238_product_of_array_except_self; +mod p134_gas_station; \ No newline at end of file diff --git a/src/problem/p134_gas_station.rs b/src/problem/p134_gas_station.rs new file mode 100644 index 0000000..e74e7cf --- /dev/null +++ b/src/problem/p134_gas_station.rs @@ -0,0 +1,66 @@ +/** + * [134] Gas Station + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { + let length = gas.len(); + let mut value = Vec::with_capacity(length * 2); + + for i in 0..length { + value.push(gas[i] - cost[i]); + } + + if value.iter().sum::() < 0 { + return -1; + } + + for i in 0..length { + value.push(value[i]); + } + + let mut pos = 0; + while pos < length { + let mut g = 0; + let mut flag = true; + + for i in 0..length { + g += value[pos + i]; + + if g < 0 { + pos = pos + i + 1; + flag = false; + break; + } + } + + if flag { + return pos as i32; + } + } + + -1 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_134() { + assert_eq!( + 3, + Solution::can_complete_circuit(vec![1, 2, 3, 4, 5], vec![3, 4, 5, 1, 2]) + ); + assert_eq!( + -1, + Solution::can_complete_circuit(vec![2, 3, 4], vec![3, 4, 3]) + ); + } +}