3-sum-closest
This commit is contained in:
parent
cbcd0a685a
commit
5edf7fa141
|
@ -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
|
Loading…
Reference in New Issue