Category | Difficulty | Likes | Dislikes |
---|
algorithms | Medium (43.03%) | 367 | - |
Tags
array
| two-pointers
Companies
bloomberg
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
1
2
3
| 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
|
Discussion | Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| struct Solution;
// @lc code=start
impl Solution {
/// ## 解题思路
/// - 双指针
/// 1. 类似15.三数和的思路
pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 {
//
let len = nums.len();
if len < 3 {
return 0;
}
let mut nums = nums;
nums.sort();
let mut res = None;
let mut diff = i32::MAX;
let c_diff = |sum, target| -> i32 { (sum as i32 - target as i32).abs() };
'outer: for i in 0..len - 2 {
let (mut l, mut r) = (i + 1, len - 1);
while l < r {
let sum = nums[i] + nums[l] + nums[r];
if c_diff(sum, target) < diff {
diff = c_diff(sum, target);
res = Some(sum);
if diff == 0 {
break 'outer;
}
}
if sum > target {
r -= 1;
} else {
l += 1;
}
}
}
res.expect("no")
}
}
// @lc code=end
|