From 8ea2584a1bff583c77562ab84e0b116e3022f884 Mon Sep 17 00:00:00 2001 From: erius Date: Tue, 30 Apr 2024 12:18:12 +0300 Subject: [PATCH] Implemented p16, minor optimization in p15 --- src/p15_3sum.rs | 11 ++++++----- src/p16_3sum_closest.rs | 22 +++++++++++++++++++--- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/p15_3sum.rs b/src/p15_3sum.rs index 8858ff4..b3e30ab 100644 --- a/src/p15_3sum.rs +++ b/src/p15_3sum.rs @@ -13,13 +13,14 @@ impl Solution { if k < nums.len() - 1 && nums[k + 1] == nums[k] { k -= 1; continue; } - match (nums[i] + nums[j] + nums[k]).cmp(&0) { - std::cmp::Ordering::Less => { j += 1; }, - std::cmp::Ordering::Greater => { k -= 1 }, - std::cmp::Ordering::Equal => { + match (nums[i] + nums[j] + nums[k]).signum() { + -1 => { j += 1; }, + 1 => { k -= 1 }, + 0 => { result.push(vec![nums[i], nums[j], nums[k]]); j += 1; k -= 1; - } + }, + _ => () } } } diff --git a/src/p16_3sum_closest.rs b/src/p16_3sum_closest.rs index c16a072..1d89769 100644 --- a/src/p16_3sum_closest.rs +++ b/src/p16_3sum_closest.rs @@ -1,8 +1,24 @@ pub struct Solution; impl Solution { - pub fn three_sum_closest(nums: Vec, target: i32) -> i32 { - - return 0; + pub fn three_sum_closest(mut nums: Vec, target: i32) -> i32 { + let mut delta = i32::MAX / 2; + nums.sort(); + for i in 0..nums.len()-2 { + if i > 0 && nums[i] == nums[i - 1] { continue; } + let (mut j, mut k) = (i + 1, nums.len() - 1); + while j < k { + let sum = nums[i] + nums[j] + nums[k]; + let new_delta = sum - target; + match new_delta.signum() { + -1 => { j += 1; }, + 1 => { k -= 1 }, + 0 => { return target; }, + _ => () + } + if new_delta.abs() < delta.abs() { delta = new_delta; } + } + } + return target + delta; } }