15. 3Sum

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]
]

一刷
有两种思路。

  1. 先排序再用双指针
    Time complexity O(n^2), space complexity O(1)

  2. 使用Two Sum的方法, 遍历 + HashMap
    Time complexity O(n^2), space complexity O(n)

HashMap 在我们需要返回indices比较有用,因为sort之后indices无法一一对应

方法1:

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums == null || nums.length<3) return res;
        Arrays.sort(nums);
        //eliminate the duplicate ones
        for(int i=0; i<nums.length-2; i++){
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int lo = i+1;
            int hi = nums.length - 1;
            while(lo < hi){
                if(nums[i] + nums[lo] + nums[hi] == 0){
                    Integer[] array = {nums[i], nums[lo], nums[hi]};
                    res.add(Arrays.asList(array));
                    hi--;
                    while(hi>=0 && nums[hi] == nums[hi+1]) hi--;
                    lo++;
                    while(lo<nums.length && nums[lo] == nums[lo-1]) {
                        lo++;
                    }
                }
                else if(nums[i] + nums[lo] + nums[hi] > 0){
                     hi--;
                }
                else {
                    lo++;
                }
            }
        }
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,940评论 0 23
  • 今天偶然发现简书,感觉很有趣,发现久违的笔墨书香,很好!完成注册后,留个言纪念一下。
    阅色美妆阅读 308评论 0 0
  • 开启内心喜悦的引擎,安驻身心,轻松愉快地回忆我今天种下的好种子。 我的人生使命:希望及由我的好种子开花结果成为幸福...
    快乐小屋刘丽华阅读 80评论 0 2
  • 几千年前,王勃就曾说过,海内存知己,天涯若比邻。大意是我们分手了,虽然天各一方,但是我们仍然像近在咫尺。 年龄的直...
    行走的淡水鱼阅读 873评论 10 7
  • 今夜似乎会想起很多,好多年前的夏夜,奶奶会给打扇子,即使睡着了,也会持续的给扇着凉…… 又想起那年小升初的考试,作...
    salit阅读 422评论 0 0