[Day9]15. 3Sum

This one is for my missed Day7. So there is still one problem needed for Day8.

DESCRIPTION:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: 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]
]

ANALYSIS:
Thank to some novel ideas learned from [16.3Sum Closest]. I finally figure out a solution, though a TLE. But some Java solutions in 'discussion' is also TLE.
Considered that ‘The solution set must not contain duplicate triplets.’, so some details are supposed to be payed attention. For example, how to choose the next DIFFERENT number--which takes me a lot of time to deal.

SOLUTION:

public static List> threeSum(int[] nums) {
    List> results = new ArrayList>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
        //deal different
        if (i == 0 || nums[i] != nums[i - 1]) {
            int starti = i + 1;
            int endi = nums.length - 1;
            while (starti < endi) {
                int sum = nums[i] + nums[starti] + nums[endi];
                if (sum == 0) {
                    List result = new ArrayList();
                    result.add(nums[i]);
                    result.add(nums[starti]);
                    result.add(nums[endi]);
                    results.add(result);

                    int lastMid = nums[starti];
                    starti++;
                    endi--;
                    //deal different
                    while (nums[starti] == lastMid && starti < endi) {
                        starti++;
                    }
                } else if (sum < 0) {
                    starti++;
                } else if (sum > 0) {
                    endi--;
                }
            }
        }
    }
    return results;
}

你可能感兴趣的:([Day9]15. 3Sum)