class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = nums[0] + nums[1] + nums[2];
for(int i = 0; i < nums.length - 2; ++i){
int l_index = i + 1;
int r_index = nums.length - 1;
while(l_index < r_index){
int sum1 = (nums[i] + nums[l_index] + nums[r_index]);
if(Math.abs(target - sum1) < Math.abs(target - result)){
result = sum1;
}
if((target - sum1) < 0){
--r_index;
}else if((target - sum1) > 0){
++l_index;
}else{
return target;
}
}
}
return result;
}
}
16. 3Sum Closest
最新推荐文章于 2019-09-08 17:34:01 发布