From 4de10fa2f37af356c3e34eaad4b7b27a532e53bd Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 26 Apr 2024 08:11:30 +0800 Subject: [PATCH] 20240426 Finished --- src/problem/mod.rs | 3 +- .../p167_two_sum_ii_input_array_is_sorted.rs | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/problem/p167_two_sum_ii_input_array_is_sorted.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 60b3922..a502593 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -112,4 +112,5 @@ mod p151_reverse_words_in_a_string; mod p28_find_the_index_of_the_first_occurrence_in_a_string; mod p68_text_justification; mod p125_valid_palindrome; -mod p392_is_subsequence; \ No newline at end of file +mod p392_is_subsequence; +mod p167_two_sum_ii_input_array_is_sorted; \ No newline at end of file diff --git a/src/problem/p167_two_sum_ii_input_array_is_sorted.rs b/src/problem/p167_two_sum_ii_input_array_is_sorted.rs new file mode 100644 index 0000000..31a02a1 --- /dev/null +++ b/src/problem/p167_two_sum_ii_input_array_is_sorted.rs @@ -0,0 +1,43 @@ +/** + * [167] Two Sum II - Input Array Is Sorted + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + let mut i = 0; + let mut j = numbers.len() - 1; + + while i < j { + let sum = numbers[i] + numbers[j]; + + if sum == target { + break; + } + else if sum < target { + i += 1; + } + else { + j -= 1; + } + + } + + vec![(i + 1) as i32 , (j + 1) as i32] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_167() { + assert_eq!(vec![1,2], Solution::two_sum(vec![2,7,11,15], 9)); + } +}