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

题目

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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值