美文网首页
[Day9]15. 3Sum

[Day9]15. 3Sum

作者: Shira0905 | 来源:发表于2017-02-08 00:14 被阅读0次

    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<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        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<Integer> result = new ArrayList<Integer>();
                        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

          本文链接:https://www.haomeiwen.com/subject/nqxvittx.html