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.

Note:

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

 

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

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

思想: 把3sum转换为2Sum,并且查找时避免重复,将重复项去除。
  1. public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
  2. ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
  3. if(num == null || num.length < 3) return res;
  4. int lg = num.length;
  5. Arrays.sort(num);
  6. for(int i=0;i<=lg-3;i++) {
  7. if(i>0 && num[i] == num[i-1]) continue;
  8. ArrayList<Integer> cur = new ArrayList<Integer>();
  9. int target = 0-num[i];
  10. int low = i+1;
  11. int high = lg-1;
  12. while(low<high) {
  13. if(num[low]+num[high]==target) {
  14. cur.add(num[i]);
  15. cur.add(num[low]);
  16. cur.add(num[high]);
  17. res.add(new ArrayList<Integer>(cur));
  18. low++;
  19. while(low<high && num[low]==num[low-1]) low++;
  20. high--;
  21. while(high>low && num[high]==num[high+1]) high--;
  22. cur.clear();
  23. } else if(num[low]+num[high]>target) {
  24. high--;
  25. while(high>low && num[high] == num[high+1]) high--;
  26. } else {
  27. low++;
  28. while(low<high && num[low]==num[low-1]) low++;
  29. }
  30. }
  31. }
  32. return res;
  33. }
posted @ 2014-07-10 23:07  purejade  阅读(95)  评论(0)    收藏  举报