/
_0016_3SumClosest.java
111 lines (103 loc) · 3.39 KB
/
_0016_3SumClosest.java
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.diguage.algorithm.leetcode;
import java.util.Arrays;
import java.util.Objects;
/**
* = 16. 3Sum Closest
*
* https://leetcode.com/problems/3sum-closest/description/[3Sum Closest - LeetCode]
*
* 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:
* [source]
* ----
* Given array nums = [-1, 2, 1, -4], and target = 1.
*
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
* ----
*
* @author D瓜哥, https://www.diguage.com/
* @since 2018-07-15 00:55
*/
public class _0016_3SumClosest {
/**
* 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.
*/
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;
}
public static void main(String[] args) {
_0016_3SumClosest solution = new _0016_3SumClosest();
int r1 = solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1);
System.out.println((2 == r1) + " : " + r1);
}
}