两数和为k
给定一个数组,试找出2个数a, b,使得a+b=k
import java.util.*;
public class task1 {
public static void main(String[] args){
int[] arr = new int[]{1,2,3,88,5,7,9,11,45,12,8,10,13,15,19,21,25,27};
Arrays.sort(arr);
int k = 11;
sumAB(arr,k);
}
public static void sumAB(int[] arr,int k){
int l=0,r=arr.length-1;
while(l < r){
int a = arr[l];
int b = arr[r];
if(a + b == k){
int[] res = new int[]{a,b};
System.out.println(Arrays.toString(res));
l++;
--r;
}else if(a + b < k){
++l;
}else{
--r;
}
}
}
}
三数和为k
给定一个数组,试找出3个数a, b, c,使得a+b+c=k
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
threeSumCore(nums,res);
return res;
}
private void threeSumCore(int[] nums,List<List<Integer>> res){
int n = nums.length;
for(int i = 0; i < n - 2; ++i){
//避免1,1,2,3情况
if(i>0 && nums[i] == nums[i-1]){
continue;
}
int l = i + 1;
int r = n - 1;
while(l < r){
int temp = nums[i] + nums[l] + nums[r];
if(temp == 0){
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
res.add(list);
//避免0,0,0情况
while(l < r && nums[l] == nums[l + 1])++l;
while(l < r && nums[r] == nums[r - 1])--r;
++l;
--r;
}else if(temp < 0){
++l;
}else{
--r;
}
}
}
}
}