# 数组类（一）：leetcode No.18. 4Sum 四数之和

class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i=0;i<nums.length-3;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length-2;j++){
if(j>i+1&&nums[j]==nums[j-1]) continue;
int lo = j+1;
int hi = nums.length-1;
while(lo<hi){
if(nums[i]+nums[j]+nums[lo]+nums[hi]==target){
while(lo<hi&&nums[lo]==nums[lo+1])  lo++;
while(lo<hi&&nums[hi]==nums[hi-1]) hi--;
hi--;
lo++;
}
else if(nums[i]+nums[j]+nums[lo]+nums[hi]>target){
hi--;
}
else{
lo++;
}
}
}
}
return list;
}
}

k数之和代码：

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution{
int len=0;
public List<List<Integer>> fourSum(int [] nums, int target){
len=nums.length;
Arrays.sort(nums);
return kSum(nums,target,4,0);
}
private ArrayList<List<Integer>> kSum(int[] nums,int target,int k,int index){
ArrayList<List<Integer>> res = new ArrayList<>();
if(index>=len){
return res;
}
if(k==2){
int i=index,j=len-1;
while(i<j){
if(target-nums[i]==nums[j]){
List<Integer> temp = new ArrayList<>();
//跳过重复
while(i<j&&nums[i]==nums[i+1]) i++;
while(i<j&&nums[j]==nums[j-1]) j--;
i++;j--;
}
//往左边移动
else if(nums[i]+nums[j]>target){
j--;
}
else{//往右边移动
i++;
}
}
}
else{
for(int i=index;i<len-k+1;i++){
//跳过重复
if(i>index&&nums[i]==nums[i-1]){
continue;
}
ArrayList<List<Integer>> temp = kSum(nums,target-nums[i],k-1,i+1);
if(temp!=null){
for(List<Integer> t : temp){
}
}
}
}
return res;
}
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客