[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<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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,132评论 0 23
  • maven中的scope表示的是标签指定的插件或者依赖,在maven项目生命周期的哪个部分有效。 可用的取值包括以...
    小孩真笨阅读 253评论 0 0
  • 我最爱在半夜无人时在我精神的旷原里嘶吼 用没人听到的破锣嗓 吼出所有一切情绪 我的喜怒哀乐 我的无人知道的喜怒哀乐...
    生活阅读 394评论 0 3
  • 原来在你眼里,那些爱都是强迫,都是伤害,原来你心里从来没有真正意义上的接受过我,所以才什么都不为我辩解,所以才走得...
    新生丫头阅读 104评论 0 0
  • 晨起略遲緩,未食,收拾行裝,將赴湛江、茂名、雲浮出差也。上午,加班甚力。中午,乘車至湛江,路上讀通鑑約一百余頁。k...
    寒窗寄傲生阅读 73评论 0 0