This commit is contained in:
Gleb Koval 2022-06-10 11:55:12 +01:00
parent 14b51882bb
commit a01ec4f2ac
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 30 additions and 0 deletions

30
3sum/sol.rs Normal file
View File

@ -0,0 +1,30 @@
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
}
}