30 lines
956 B
Rust
30 lines
956 B
Rust
|
use std::{collections::{HashMap, HashSet}, cmp::Ordering};
|
||
|
|
||
|
impl Solution {
|
||
|
pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
|
||
|
nums.sort();
|
||
|
let mut out = vec![];
|
||
|
for idx in 0..nums.len() {
|
||
|
if idx != 0 && nums[idx] == nums[idx - 1] {
|
||
|
continue;
|
||
|
}
|
||
|
let mut l = idx + 1;
|
||
|
let mut r = nums.len() - 1;
|
||
|
while l < r {
|
||
|
let sum = nums[idx] + nums[l] + nums[r];
|
||
|
match sum.cmp(&0) {
|
||
|
Ordering::Greater => r -= 1,
|
||
|
Ordering::Less => l += 1,
|
||
|
Ordering::Equal => {
|
||
|
out.push(vec![nums[idx], nums[l], nums[r]]);
|
||
|
l += 1;
|
||
|
while nums[l] == nums[l - 1] && l < r {
|
||
|
l += 1;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
out
|
||
|
}
|
||
|
}
|