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; } }