20240426 Finished
This commit is contained in:
parent
d27f640226
commit
4de10fa2f3
|
@ -113,3 +113,4 @@ mod p28_find_the_index_of_the_first_occurrence_in_a_string;
|
|||
mod p68_text_justification;
|
||||
mod p125_valid_palindrome;
|
||||
mod p392_is_subsequence;
|
||||
mod p167_two_sum_ii_input_array_is_sorted;
|
43
src/problem/p167_two_sum_ii_input_array_is_sorted.rs
Normal file
43
src/problem/p167_two_sum_ii_input_array_is_sorted.rs
Normal file
|
@ -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<i32>, target: i32) -> Vec<i32> {
|
||||
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));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user