Thought:
The basic pattern is just like the 3Sum.
Use a flag to store the difference between sum and the target, when we encounter a smaller difference ,we should update the difference and also update the result at the same time.
It is a O(n^2) solution.
Code:
public class Solution {
public int threeSumClosest(int[] num, int target) {
int dif = Integer.MAX_VALUE;
int result = target;
Arrays.sort(num);
for(int i = 0;i < num.length; i++){
int j = i + 1;
int k = num.length - 1;
while(j < k){
int sum = num[j] + num[k] + num[i];
if(sum == target){
return target;
}else if(sum > target){
k--;
}else{
j++;
}
if(dif > Math.abs(sum-target)){
result = sum;
}
dif = Math.min(dif, Math.abs(sum-target));
}
}
return result;
}
}
Second Round Code:
public class Solution {
public int threeSumClosest(int[] num, int target) {
int dif = Integer.MAX_VALUE;
int result = target;
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
int j = i + 1;
int k = num.length - 1;
while (j < k) {
int temp = num[i] + num[j] + num[k];
if (temp == target) return target;
if (temp < target) j++;
else k--;
if (dif > Math.abs(temp - target)) {
dif = Math.abs(temp - target);
result = temp;
}
}
}
return result;
}
}
No comments:
Post a Comment