15. 三数之和 (二数之和,四数之和)
先看一下两数之和的解:
给一个有序数组,返回组成和为指定值的元组
public static void main(String[] args) {
int[] arr={2, 2 ,4, 5 ,9 ,10 ,12};
getPair(arr,14);
}
public static void getPair(int[] nums,int aim){
if(nums==null||nums.length<2){
return;
}
int L=0;
int R=nums.length-1;
while (L<R){
//arr[L]+arr[R]> R-- < L++
if(nums[L]+nums[R]>aim){
R--;
}else if(nums[L]+nums[R]<aim){
L++;
}else{
if(L==0||nums[L-1]!=nums[L]){//避免重复值
System.out.println("left="+nums[L]+",right="+nums[R]);
}
L++;
R--;
}
}
}
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// -4 -1 -1 0 1 2
List<List<Integer>> resultList=new ArrayList<>();
if(nums==null || nums.length<3){
return resultList;
}
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(nums[i]>0){
return resultList;
}
if(i>0 && nums[i]==nums[i-1]){
continue;
}
int target=-nums[i];
int L=i+1;
int R=nums.length-1;
while(L<R){
if(nums[L]+nums[R]==target){
List<Integer> ans=new ArrayList<>();
ans.add(nums[i]);
ans.add(nums[L]);
ans.add(nums[R]);
resultList.add(ans);
L++;
R--;
while(L<R && nums[L]==nums[L-1]){
L++;
}
while(L<R && nums[R]==nums[R+1]){
R--;
}
}else if (nums[L]+nums[R]<target){
L++;
}else{
R--;
}
}
}
return resultList;
}
}
18. 四数之和
给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] :
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> resultList=new ArrayList<>();
if(nums==null||nums.length<=3){
return resultList;
}
Arrays.sort(nums);
for(int i=0;i<nums.length-3;i++){
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int thirdSumTarget=target-nums[i];
for(int j=i+1;j<nums.length-2;j++){
if(j>i+1&&nums[j]==nums[j-1]){
continue;
}
int twoSumTarget=thirdSumTarget-nums[j];
int L=j+1;
int R=nums.length-1;
while(L<R){
if(nums[L]+nums[R]>twoSumTarget){
R--;
}else if(nums[L]+nums[R]<twoSumTarget){
L++;
}else{
List<Integer> ans=new ArrayList<>();
ans.add(nums[i]);
ans.add(nums[j]);
ans.add(nums[L]);
ans.add(nums[R]);
resultList.add(ans);
L++;
R--;
while(L<R && nums[L]==nums[L-1]){
L++;
}
while(L<R && nums[R]==nums[R+1]){
R--;
}
}
}
}
}
return resultList;
}
}

浙公网安备 33010602011771号