topic
Given an array of n integers nums and a target value target. Find the three integers in nums so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs. link
Ideas
Violence, 3 cycles. .
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
int res = Integer.MAX_VALUE - 1;
for(int i = 0;i < len;i++){
for(int j = i + 1;j < len;j++){
for(int k = j + 1;k < len;k++){
int t = nums[i] + nums[j] + nums[k];
if(t == target){
return target;
}else{
if(Math.abs(t - target) < Math.abs(res - target)){
res = t;
}
}
}
}
}
return res;
}
}
The outer layer is fixed with one num[i]
, and the double pointer looks for the remaining two numbers, which are greater than the left and right borders, and less than the right and left borders. Each time the judgment is closer target
, it is updated res
.
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
int res = nums[0] + nums[1] + nums[2];
for(int i = 0;i < len;i++){
int j = i + 1;
int k = len - 1;
while(j < k){
int t = nums[i] + nums[j] + nums[k];
if(Math.abs(t - target) < Math.abs(res - target)){
res = t;
}
if(t > target){
k--;
}else if(t < target){
j++;
}else{
return target;
}
}
}
return res;
}
}