3Sum

原题目:


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

For example, given array S = {-1 0 1 2 -1 -4},

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

思路,首先

这道题的O(n3)很好想,就是一个3个for循环的遍历搜素。

通过阅读找到这篇博文

http://tech-wonderland.net/blog/summary-of-ksum-problems.html

借鉴于2 sum的方法 即在排列好的array中搜索两个数的和为sum只需要O(n)的方法

所以3sum来说的话O(logn*n)的时间几乎可以忽略不计

代码:

public class Solution {
//新的arraylist用来存放结果
List<List<Integer>> res = new ArrayList<List<Integer>>();

public List<List<Integer>> threeSum(int[] num){
int length = num.length;
if(length < 3)
return res;

quicksort(num, 0, length - 1);
for(int i = 0; i < length - 2; i++){
if(i > 0 && num[i] == num[i-1]) continue;
int pivox = num[i];
find(num, i+1, length-1, pivox);
}

return res;
}

public void find(int[]num, int start, int end, int pivotvalue){
//利用sum的方法进行时间复杂度为O(n)的计算
int scanup = start;
int scandown = end; 
while(scanup < scandown){         //循环的条件
int sum = num[scanup] + num[scandown];
if(sum + pivotvalue == 0){    //分三种情况 1 三个数的和为0
List<Integer> zuhe= new ArrayList<Integer>();
zuhe.add(num[start]);
zuhe.add(num[end]);
zuhe.add(pivotvalue);
res.add(zuhe);
while(scanup < scandown && num[scanup] == num[scanup+1])
scanup++;
while(scanup < scandown && num[scandown] == num[scandown-1])
scandown--;
scandown--;
scanup++;
}

else if(sum + pivotvalue > 0){   //三个数的和大于0
scandown --;
}

else{                            //三个数的和小于0
scanup++;
}

}
}


//这里需要一个quicksort的方法

//时间复杂度为O(nlogn)
public void quicksort(int[]num, int start, int end){
if(start >= end)
return;
int indexpivox = start;
int scanup = start+1;
int scandown = end;
while(scanup <= scandown){
while(scanup < end && num[scanup] <= num[indexpivox])
scanup++;
while(scandown > start && num[scandown] >= num[indexpivox])
scandown--;
if(scanup < scandown){
swap(num, scanup, scandown);
scanup++;
scandown--;
}
}
swap(num, indexpivox, scandown);
quicksort(num, start,scandown);
quicksort(num, scandown+1, end);
}

public void swap(int[]num, int scanup, int scandown){
int tem;
tem = num[scanup];
num[scanup] = num[scandown];
num[scandown] = tem;
}

}


quicksort的算法还是有bug



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值