Link: https://oj.leetcode.com/problems/3sum-closest/
这题和3Sum 几乎一样。下面是我一次写的代码,基本正确。
Time: O(n^2), Space: O(1)
public class Solution {
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int gap = Integer.MAX_VALUE;
int result = Integer.MAX_VALUE;
for(int i = 0; i < num.length; i++){
if(i != 0 && num[i] == num[i-1]) continue;//pass duplicate elements
int j = i+1;
int k = num.length - 1;
while(j < k){
int sum = num[i] + num[j] + num[k];
if(Math.abs(target - sum) < gap){
result = sum;
}
}
}
return result;
}
}
完整解法:
public class Solution {
public int threeSumClosest(int[] num, int target) {
int sum = 0;
int result = 0;
int diff = Integer.MAX_VALUE;
Arrays.sort(num);
for(int i = 0; i < num.length-1;i++){
int j = i+1;
int k = num.length-1;
while(j < k){
sum = num[i] + num[j] + num[k];
if(sum == target) return sum;
if(Math.abs(sum-target) < diff){
diff = Math.abs(sum-target);
result = sum;
}
if(sum < target){
j++;
}
else if(sum > target){
k--;
}
}
}
return result;
}
}
相关题目: 3Sum