class Solution {
public int threeSumClosest(int[] nums, int target) {
int best = nums[0] + nums[1] + nums[2];
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
if(i > 0 && nums[i - 1] == nums[i]) continue;
int first = i + 1, second = nums.length - 1;
while(first < second){
int sum = nums[i] + nums[first] + nums[second];
if(Math.abs(sum - target) < Math.abs(best - target)){
best = sum;
}
if(sum > target) {
second--;
while(first < second && nums[second] == nums[second + 1]) second--;
}else if(sum < target) {
first++;
while(first < second && nums[first - 1] == nums[first]) first++;
}else return sum;
}
}
return best;
}
}
16. 最接近的三数之和
最新推荐文章于 2022-05-05 19:59:49 发布