leet-code/3-sum-closest/sol.rs

34 lines
871 B
Rust

/*
* @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