From 3e15c5bd7873092b0feb7c4ebc840a219d119fa8 Mon Sep 17 00:00:00 2001 From: erius Date: Fri, 19 Apr 2024 13:22:30 +0300 Subject: [PATCH] Problem 15 prototype implementation --- src/bin/15_3sum.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/bin/15_3sum.rs b/src/bin/15_3sum.rs index 794535d..f5c0f2b 100644 --- a/src/bin/15_3sum.rs +++ b/src/bin/15_3sum.rs @@ -1,8 +1,26 @@ fn main() { - + println!("{:?}", three_sum(vec![-1,0,1,2,-1,-4])); } -pub fn three_sum(nums: Vec) -> Vec> { - - return vec![]; +// TODO: fix and optimize +pub fn three_sum(mut nums: Vec) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut seen = std::collections::HashSet::::with_capacity(nums.len()); + let mut seen2 = std::collections::HashSet::::with_capacity(nums.len()-1); + nums.sort(); + for i in 0..nums.len()-2 { + if seen.contains(&nums[i]) { continue; } + for j in i+1..nums.len()-1 { + if seen2.contains(&nums[j]) { continue; } + for k in j+1..nums.len() { + if nums[i] + nums[j] + nums[k] == 0 { + result.push(vec![nums[i], nums[j], nums[k]]); + } + } + seen2.insert(nums[j]); + } + seen.insert(nums[i]); + seen2.clear(); + } + return result; }