3Sum Closest
实现:
去重在这里已经不重要了,可以忽略,重复的数不影响最终结果。
记得到初始化int res = numbers[0] + numbers[1] + numbers[numbers.length - 1],而不是0。和two sum closest不一样,前者是求different。这道题的result是会参与比较影响结果的:Math.abs(sum - target) < Math.abs(res - target)
代码如下:
public class Solution {
/*
* @param numbers: Give an array numbers of n integer
* @param target: An integer
* @return: return the sum of the three integers, the sum closest target.
*/
public int threeSumClosest(int[] numbers, int target) {
// write your code here
// write your code here
Arrays.sort(numbers);
int res = numbers[0] + numbers[1] + numbers[numbers.length - 1];
for(int i = 0; i < numbers.length - 2; i++) {
int left = i + 1;
int right = numbers.length - 1;
while(left < right) {
int sum = numbers[left] + numbers[right] + numbers[i];
if (sum < target) {
left++;
} else {
right--;
}
if(Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
}
}
return res;
}
}
评论
发表评论