leetcode解题方案--015--3 sum

来源:互联网 发布:乐视视频有mac版吗 编辑:程序博客网 时间:2024/06/07 08:56

题目

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

分析

题目隐含的条件,不能有重复的list,不能每个小list必须从小到大排序。

我的思路有两个
1 将n^3转化为2sum。leetcode第一题就是一道2sum,我用hashmap做的
2 使用数组左右指针。

实践来看,第二种方法更优。

这个有两个测试例没过。
稍后我会分析一下时间长的原因。

class Solution {     public List<List<Integer>> threeSum(int[] nums) {        HashSet<List<Integer>> set = new HashSet<>();        List<List<Integer>> list = new ArrayList<>();        for (int i = 0; i < nums.length; i++) {            Map<Integer, Integer> map = new HashMap<Integer, Integer>();            for (int k = i + 1; k < nums.length; k++) {                if (map.containsKey(nums[k])) {                    List<Integer> tmpList = new ArrayList<>();                    tmpList.add(nums[i]);                    tmpList.add(nums[k]);                    tmpList.add( 0 - nums[i] - nums[k]);                    Collections.sort(tmpList);                    set.add(tmpList);                } else {                    map.put(0 - nums[i] - nums[k], k);                }            }        }        list.addAll(set);        return list;    }}

这是左右指针的方法,去掉了放进set去重的部分,时间更短。
那如何保证不重复呢,关键点在于排序。一个有序的数组,相同的数就会相邻。
在这个程序中 if (i == 0 || (i > 0 && nums[i] != nums[i-1]))会去掉-sum相同的情况,而while (k1 < k2 && nums[k1] == nums[k1+1]) k1++;
while (k1 < k2 && nums[k2] == nums[k2-1]) k2–;会去掉指针移动时相同的情况。

 public static List<List<Integer>> threeSum(int[] nums) {        Arrays.sort(nums);        List<List<Integer>> list = new ArrayList<>();        for (int i = 0; i < nums.length - 2; i++) {            if (i == 0 ||  (i > 0 && nums[i] != nums[i-1])) {                int k1 = i + 1;                int k2 = nums.length - 1;                while (k2-k1>=1) {                    if (nums[i] + nums[k1] + nums[k2] == 0) {                        list.add(Arrays.asList(nums[i], nums[k1], nums[k2]));                        while (k1 < k2 && nums[k1] == nums[k1+1]) k1++;                        while (k1 < k2 && nums[k2] == nums[k2-1]) k2--;                        k1++;k2--;                    } else if (nums[i] + nums[k1] + nums[k2] > 0) {                        k2--;                    }else {                        k1++;                    }                }            }        }        return list;    }
原创粉丝点击