leetcode003:4 sum

leetcode 专栏收录该内容
5 篇文章 0 订阅

4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

• Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
• The solution set must not contain duplicate quadruplets.

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length>=4){
//qSort(num,0,num.length-1);
bubbleSort(num);
for(int i=0;i<num.length-3;i++){
if(i!=0&&num[i]==num[i-1]){//去重
continue;
}
int a = num[i];
for(int j=i+1;j<num.length-2;j++){
if(j!=i+1&&num[j]==num[j-1]){//去重
continue;
}
int b = num[j];
int k = j+1;
int n = num.length-1;
while(k<n){
if(k!=j+1&&num[k]==num[k-1]){//去重
k++;
continue;
}
int c = num[k];
if(n<num.length-1&&num[n]==num[n+1]){//去重
n--;
continue;
}
int d = num[n];
int sum = a+b+c+d;//多存一个数，可以免去多次加法操作
if(sum == target){
ArrayList<Integer> al = new ArrayList<Integer>();
n--;
continue;
}else if(sum>target){
n--;
}else{
k++;
}
}
}
}
}
return result;
}
public void bubbleSort(int[] array){
if(array.length == 0)return ;
for(int i=0;i<array.length-1;i++){
for(int j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
swap(array, j, j+1);
}
}
}
}
public void swap(int[] array,int i,int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//快速排序，可忽略
public static void qSort(int[] num,int low,int high){
if(low<high){
int pivotloc = partition(num,low,high);
qSort(num, low, pivotloc-1);
qSort(num, pivotloc+1, high);
}
}
public static int partition(int[] num,int low,int high){
int mid = num[low];
int pivotkey = num[low];
while(low<high){
while(low<high&&num[high]>=pivotkey){
--high;
}
num[low] = num[high];
while(low<high&&num[low]<=pivotkey){
++low;
}
num[high]=num[low];
}
num[low] = mid;
return low;
}

• 0
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

01-26 80

08-07 536

Shellphon

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。