11/08/2012

3 Sum


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)

public class Solution {
    public ArrayList> threeSum(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Arrays.sort(num);
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        for (int i = 0; i <= num.length - 3; i++) {
            int a = num[i];
            int j = i+1;
            int k = num.length - 1;
            while (j < k) {
                int b = num[j];
                int c = num[k];
                if (a + b + c == 0) {
                    ArrayList sublist = new ArrayList();
                    sublist.add(a);
                    sublist.add(b);
                    sublist.add(c);
                    list.add(sublist);
                    j++;
                    while (num[j] == num[j - 1] && j - 1 != i && j < k) {
                        j++;
                    }
                    k--;
                    while (num[k] == num[k + 1] && j < k) {
                        k--;
                    } 
                }
                else if (a + b + c < 0) {
                    j++;
                    while (num[j] == num[j - 1] && j - 1 != i && j < k) {
                        j++;
                    }
                }
                else {
                    k--;
                    while (num[k] == num[k + 1] && j < k) {
                        k--;
                    } 
                }
            }
            
            while (i + 1 <= num.length - 3 && num[i + 1] == num[i]) {
                i++;
            }
        }
        
        return list;
    }
}

No comments:

Post a Comment