|
| 1 | +/// Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. |
| 2 | +/// |
| 3 | +/// You may assume that each input would have **exactly one solution**, and you may not use the same element twice. |
| 4 | +/// |
| 5 | +/// You can return the answer in any order. |
| 6 | +/// |
| 7 | +/// #### Example 1: |
| 8 | +/// > **Input:** ```nums = [2,7,11,15], target = 9``` |
| 9 | +/// |
| 10 | +/// > **Output:** ```[0,1]``` |
| 11 | +/// |
| 12 | +/// > **Explanation:** ```Because nums[0] + nums[1] == 9, we return [0, 1].``` |
| 13 | +/// #### Example 2: |
| 14 | +/// > **Input:** ```nums = [3,2,4], target = 6``` |
| 15 | +/// |
| 16 | +/// > **Output:** ```[1,2]``` |
| 17 | +/// #### Example 3: |
| 18 | +/// > **Input:** ```nums = [3,3], target = 6``` |
| 19 | +/// |
| 20 | +/// > **Output:** ```[0,1]``` |
| 21 | +/// |
| 22 | +/// #### Constraints: |
| 23 | +/// - <code>2 <= nums.length <= 10<sup>4</sup></code> |
| 24 | +/// - <code>-10<sup>9</sup> <= nums\[i\] <= 10<sup>9</sup></code> |
| 25 | +/// - <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code> |
| 26 | +/// - **Only one valid answer exists.** |
| 27 | +pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { |
| 28 | + let mut nums: Vec<(usize, i32)> = nums.into_iter().enumerate().collect::<Vec<(usize, i32)>>(); |
| 29 | + nums.sort_unstable_by_key(|&(_, v)| v); |
| 30 | + for (i, (k, v)) in nums.iter().enumerate() { |
| 31 | + match nums[i + 1..].binary_search_by_key(&(target - *v), |&(_, b)| b) { |
| 32 | + Ok(j) => { |
| 33 | + return vec![*k as i32, nums[j + i + 1].0 as i32]; |
| 34 | + } |
| 35 | + Err(_) => {} |
| 36 | + } |
| 37 | + } |
| 38 | + unreachable!(); |
| 39 | +} |
0 commit comments