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.
时间复杂度:O(n^2)
空间复杂度:O(1)
class Solution {
public int threeSumClosest(int[] nums, int target) {
int length = nums.length;
if(length < 3)
return -1;
int result = 0;
int minDiff = Integer.MAX_VALUE;
Arrays.sort(nums);
for(int i = 0;i < length;i++){
int start = i + 1;
int end = length - 1;
while(start < end){
int tempSum = nums[i] + nums[start] + nums[end];
if(tempSum == target){
return tempSum;
}
if(Math.abs(tempSum - target) < minDiff){
minDiff = Math.abs(tempSum - target);
result = tempSum;
}
if(tempSum - target > 0){
end--;
}else{
start++;
}
}
}
return result;
}
}