find three elements in a sorted array O(n^2) fix the first element and find the remaining two elements in the right subvector
(nums: Vec<i32>)
| 9 | /// fix the first element and find the remaining two elements |
| 10 | /// in the right subvector |
| 11 | pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> { |
| 12 | let mut nums = nums.clone(); |
| 13 | nums.sort(); |
| 14 | let mut ret: Vec<Vec<i32>> = Vec::new(); |
| 15 | if nums.len() < 3 { return ret } |
| 16 | for i in 0..nums.len()-2 { |
| 17 | if nums[i] > 0 { break } |
| 18 | else if i > 0 && nums[i] == nums[i - 1] { continue } |
| 19 | else { |
| 20 | let mut l = i + 1; |
| 21 | let mut r = nums.len() - 1; |
| 22 | while l < r { |
| 23 | if nums[i] + nums[l] + nums[r] < 0 { |
| 24 | l += 1 |
| 25 | } else if nums[i] + nums[l] + nums[r] > 0 { |
| 26 | r -= 1 |
| 27 | } else { |
| 28 | ret.push(vec![nums[i], nums[l], nums[r]]); |
| 29 | while l < r && nums[l] == nums[l + 1] { |
| 30 | l += 1 |
| 31 | } |
| 32 | l += 1; |
| 33 | while l < r && nums[r - 1] == nums[r] { |
| 34 | r -= 1 |
| 35 | } |
| 36 | r -= 1; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | ret |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[cfg(test)] |