题目:
思路:
1.先将输入的数组进行排序
2.对第一个数据进行判断,第一个必须位负数,大于零才可能三位数的之和为零
3.使用双指针,从第一个数据的后一位开始向后循环进位,后面的指针从最后一位开始进位
4.要进行去重,因为要考虑例如[-1,-1,0,2,2]因为数组中有相同数据,所以在循环的时候会多次运算一遍,但是得出结果只能是一组相同的,所以进行判断,相同则直接跳过这一位;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
if(nums[i] > 0){
break;
}
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
int start = i + 1;
int end = nums.length - 1;
while(start < end){
if(nums[i] + nums[start] + nums[end] == 0){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[start]);
list.add(nums[end]);
res.add(list);
while (start<end && nums[start+1] == nums[start]){
start++;
}
start++;
while (start<end && nums[end-1] == nums[end]){
end--;
}
end--;
}
else if(nums[i] + nums[start] + nums[end] > 0){
end--;
}
else{
start++;
}
}
}
return res;
}
}
题目:
思路:
1.先假设数组的前三位值之和为最接近或者等于输入值。
2.其次使用双指针,从第一位数与双指针指向的值相加,将前面定义的三位数之和与 后面循环所得到的三位数之和与输入值做差
3.使用绝对值进行比较,那个绝对值小赋值为最为接近,等循环完后输出最为接近值
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int approach = nums[0] + nums[1] + nums[2];
int left,right;
for (int i = 0; i < nums.length; i++) {
left = i + 1;
right = nums.length- 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (Math.abs(sum - target) < Math.abs(approach - target)){
approach = sum;
}
if (approach == target) {
return target;
} else if (sum > target) {
right --;
} else if (sum < target) {
left ++;
}
}
}
return approach;
}
}