05 August 2008
Given an array
of n integers and an integer 1
nums
, find three integers in 1
target
such that the sum is closest to 1
nums
. Return the sum of the three integers. You may assume that each input would have exactly one solution.1
target
Example:
1
2
3
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
找到数组中的一个triplet三个数的和距离target的差值相比其它triplets来说是最小的,并返回这个triplet的和,因为不是返回所有可能的triplets,所以不需要去重了。这是上一道题的延伸,思路类似,先排序,然后确定一个index,剩下的两个indices两头扫描。
同样,时间复杂度: O(nlogn) + O(n^2) = O(n^2);空间复杂度O(n)。
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
class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) {
return 0;
}
int result = 0;
int min = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int first = 0; first <= nums.length - 3; first++) {
int second = first + 1, third = nums.length - 1;
while (second < third) {//循环一轮找到最小的min
int sum = nums[first] + nums[second] + nums[third];
if (Math.abs(sum - target) < min) {
min = Math.abs(sum - target);
result = sum;
}
if (sum == target) {//等于target那就是差距最小了,直接返回
return sum;
} else if (sum < target) {
second++;
} else {
third--;
}
}
}
return result;
}
}