3-sum-closest

This commit is contained in:
Gleb Koval 2022-09-01 17:06:45 +00:00
parent cbcd0a685a
commit 5edf7fa141
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 33 additions and 0 deletions

33
3-sum-closest/sol.rs Normal file
View File

@ -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<i32>, 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