From a01ec4f2ace43b7134f79c2d0c864416d18c26d6 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Fri, 10 Jun 2022 11:55:12 +0100 Subject: [PATCH] 3sum --- 3sum/sol.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 3sum/sol.rs diff --git a/3sum/sol.rs b/3sum/sol.rs new file mode 100644 index 0000000..f26adbe --- /dev/null +++ b/3sum/sol.rs @@ -0,0 +1,30 @@ +use std::{collections::{HashMap, HashSet}, cmp::Ordering}; + +impl Solution { + pub fn three_sum(mut nums: Vec) -> Vec> { + 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 + } +} \ No newline at end of file