|
@@ -0,0 +1,68 @@
|
|
|
+struct Solution;
|
|
|
+impl Solution {
|
|
|
+ pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
|
|
|
+ let n = numbers.len();
|
|
|
+ for i in 0..n-1 {
|
|
|
+ let elem = target - numbers[i];
|
|
|
+
|
|
|
+ if let Some(e) = Self::binary_search(&numbers, elem, i+1, n-1) {
|
|
|
+ return vec![i as i32+1, e];
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ vec![]
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ fn binary_search(numbers: &Vec<i32>, elem: i32, left: usize, right: usize) -> Option<i32> {
|
|
|
+ if numbers[left] > elem {
|
|
|
+ return None;
|
|
|
+ }
|
|
|
+ let mut left = left;
|
|
|
+ let mut right = right;
|
|
|
+ while left <= right {
|
|
|
+ let mid = (left + right) / 2;
|
|
|
+ if numbers[mid] == elem {
|
|
|
+ return Some(1 + mid as i32);
|
|
|
+ }
|
|
|
+
|
|
|
+ if numbers[mid] > elem {
|
|
|
+ if mid == 0 {
|
|
|
+ return None;
|
|
|
+ }
|
|
|
+ right = mid - 1;
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if numbers[mid] < elem {
|
|
|
+ left = mid + 1;
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ None
|
|
|
+
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_two_sum() {
|
|
|
+ let numbers = vec![2,7,11,15];
|
|
|
+ let target = 9;
|
|
|
+ let res = Solution::two_sum(numbers, target);
|
|
|
+ assert_eq!(res, vec![1,2]);
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_two_sum2() {
|
|
|
+ let numbers = vec![5,25,75];
|
|
|
+ let target = 100;
|
|
|
+ let res = Solution::two_sum(numbers, target);
|
|
|
+ assert_eq!(res, vec![2,3]);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|