From 5edf7fa141560abcd1155833f415692be4429b68 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Thu, 1 Sep 2022 17:06:45 +0000 Subject: [PATCH] 3-sum-closest --- 3-sum-closest/sol.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 3-sum-closest/sol.rs diff --git a/3-sum-closest/sol.rs b/3-sum-closest/sol.rs new file mode 100644 index 0000000..a393af9 --- /dev/null +++ b/3-sum-closest/sol.rs @@ -0,0 +1,33 @@ + +/* + * @lc app=leetcode id=16 lang=rust + * + * [16] 3Sum Closest + */ +struct Solution {} + +// @lc code=start +use std::cmp::Ordering; + +impl Solution { + pub fn three_sum_closest(mut nums: Vec, target: i32) -> i32 { + nums.sort_unstable(); + let mut result = nums[0] + nums[1] + nums[2]; + for (i, &n) in nums.iter().enumerate() { + let (mut l, mut r) = (i + 1, nums.len() - 1); + while l < r { + let sum = n + nums[l] + nums[r]; + if (target - sum).abs() < (target - result).abs() { + result = sum; + } + match sum.cmp(&target) { + Ordering::Equal => return sum, + Ordering::Less => l += 1, + Ordering::Greater => r -= 1 + } + } + } + result + } +} +// @lc code=end