BiruLyu
7/15/2017 - 1:55 AM

## 16. 3Sum Closest(#).java

``````public class Solution {
public int threeSumClosest(int[] nums, int target) {

int len =  nums.length;
if (len == 3)
return nums[0] + nums[1] + nums[2];

Arrays.sort(nums);
int tLow, tHigh;
tLow = target;
tHigh = target + 1;

while (true) {
if (checkContains(nums, tLow))
return tLow;
if (checkContains(nums, tHigh))
return tHigh;
tLow--;
tHigh++;
}
}

private boolean checkContains(int[] nums, int target) {
int len = nums.length;
for (int i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
int a, b, c;
int low = i + 1, high = len - 1;
a = nums[i];

while (low < high) {
b = nums[low];
c = nums[high];
if (a + b + c > target) {
high--;
} else if (a + b + c < target) {
low++;
} else {
return true;
}
}
}
return false;
}
}``````
``````public class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = nums[0] + nums[1] + nums[2];
Arrays.sort(nums);

for (int i = 0; i < nums.length - 2; i++) {
//element1 = nums[i];
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int tempSum = nums[i] + nums[j] + nums[k];
if (tempSum == target) {
return target;
}else if (Math.abs(tempSum - target) < Math.abs(res - target)) {
res = tempSum;
}
if (tempSum > target) {
k--;
}else {
j++;
}
}// while loop
}//for loop
return res;

}
}``````