Skip to content

Commit c96cc25

Browse files
committed
Added solution of problem 167
1 parent 97a9cfd commit c96cc25

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ pub mod s0155_min_stack;
9393
pub mod s0162_find_peak_element;
9494
pub mod s0164_maximum_gap;
9595
pub mod s0165_compare_version_numbers;
96+
pub mod s0167_two_sum_ii_input_array_is_sorted;
9697
pub mod s0231_power_of_two;
9798
pub mod s0232_implement_queue_using_stacks;
9899
pub mod s0234_palindrome_linked_list;
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
2+
let mut left: usize = 0;
3+
let mut right: usize = numbers.len() - 1;
4+
5+
while left < right {
6+
if numbers[left] + numbers[right] == target {
7+
return vec![left as i32 + 1, right as i32 + 1];
8+
} else if numbers[left] + numbers[right] > target {
9+
right -= 1;
10+
} else {
11+
left += 1;
12+
}
13+
}
14+
15+
vec![]
16+
}
17+
18+
#[cfg(test)]
19+
mod test {
20+
use super::*;
21+
22+
#[test]
23+
fn test_case_1() {
24+
assert_eq!(two_sum(vec![2, 7, 11, 15], 9), [1, 2]);
25+
}
26+
27+
#[test]
28+
fn test_case_2() {
29+
assert_eq!(two_sum(vec![2, 3, 4], 6), [1, 3]);
30+
}
31+
32+
#[test]
33+
fn test_case_3() {
34+
assert_eq!(two_sum(vec![-1, 0], -1), [1, 2]);
35+
}
36+
}

0 commit comments

Comments
 (0)