友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
16. 3Sum Closest
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Runtime: 4 ms, faster than 96.20% of Java online submissions for 3Sum Closest.
*
* Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for 3Sum Closest.
*
* @author D瓜哥 · https://www.diguage.com
* @since 2018-07-15 00:55
*/
public int threeSumClosest(int[] nums, int target) {
if (Objects.isNull(nums)) {
return target;
}
Arrays.sort(nums);
int length = nums.length;
int result = 0;
int difference = Integer.MAX_VALUE;
for (int head = 0; head < length; head++) {
int midd = head + 1;
int tail = length - 1;
while (midd < tail) {
int sum = nums[head] + nums[midd] + nums[tail];
if (sum > target) {
while (midd < tail && nums[tail - 1] == nums[tail]) {
tail--;
}
tail--;
} else if (sum < target) {
while (midd < tail && nums[midd] == nums[midd + 1]) {
midd++;
}
midd++;
} else {
return target;
}
int tempDiff = Math.abs(sum - target);
if (tempDiff < difference) {
result = sum;
difference = tempDiff;
}
}
}
return result;
}
/**
* Runtime: 73 ms, faster than 7.18% of Java online submissions for 3Sum Closest.
*
* Memory Usage: 36.7 MB, less than 100.00% of Java online submissions for 3Sum Closest.
*/
public int threeSumClosestO3(int[] nums, int target) {
if (Objects.isNull(nums)) {
return target;
}
int length = nums.length;
if (length <= 3) {
int result = 0;
for (int i = 0; i < length; i++) {
result += nums[i];
}
return result;
}
int result = 0;
int difference = Integer.MAX_VALUE;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
for (int k = j + 1; k < length; k++) {
int sum = nums[i] + nums[j] + nums[k];
int temp = Math.abs(target - sum);
if (temp < difference) {
difference = temp;
result = sum;
}
}
}
}
return result;
}