Leetcode1-100: 15. 3Sum

问题描述

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1,  0, 1],
  [-1, -1, 2]
]

题目要求是输入一个数组,给出所有和为0的三元组的集合。

解题思路

  1. Brute force 生成所有三元组,然后判断是否需要加入结果集中(可以先排序然后实现来确保不加入重复的三元组)
  2. 排序扩展法, 先排序,确定一个元素之后,找后续的元素中有没有两个元素的和是选中元素的负数。由于先排序了,可以用头尾指针线性的过一遍就可以找到对应的元素。需要注意的是由于不能加入重复的三元组,所以添加了一组后可以移动头尾指针来确保没有重复的元素加进去。

代码实现

implement 1 Brute force

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 2; i++) {
            for(int j = i + 1; j < nums.length - 1; j++) {
                for(int k = j + 1; k < nums.length; k++) {
                    if(nums[i]+nums[j]+nums[k] == 0) {
                        if(!(res.contains(Arrays.asList(nums[i], nums[j], nums[k])))){
                            res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                        }
                    }
                }
            }
        }
        return res;
    }

在这里插入图片描述
果然,时间复杂度太高了,遇到很长的串就超时了。

implement 2 扩展中心法

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new LinkedList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 2; i++) {
            int start = i+1, end = nums.length - 1, target = -nums[i];
            while(start < end) {
                if(nums[start]+nums[end] > target)
                    end--;
                else if(nums[start]+nums[end] < target)
                    start++;
                else {
                    res.add(Arrays.asList(nums[i], nums[start], nums[end]));
                    //去掉重复的元素,防止start指向重复的元素
                    while(start < nums.length - 1 && nums[start] == nums[start+1]) start++;
                    //去掉重复的元素,防止end指向重复的元素
                    while(end > 0 && nums[end] == nums[end-1]) end--;
                    start++;
                    end--;
                }     
            }
            //去掉重复的元素,防止i指向重复的元素
            while(i < nums.length - 1 && nums[i] == nums[i+1]) i++;
        }
        return res;
    }

在这里插入图片描述

复杂度分析

对于实现1的brute force方法,时间复杂度是O(n4)(因为ArrayList.contains()函数也需要线性的时间复杂度), 空间复杂度是O(C3n)
对于实现2的方法, 时间复杂度是O(n2), 空间复杂度是O(C3n)

分析

这题的排序是比较重要的一点,因为排完序之后线性查找可以节省很多时间。
另外,leetcode似乎对于O(n2)以上的算法几乎不可能通过,因为经常会有很长的输入。

PS:感觉这样写出所有算法的行为不大有效,今天明明直接用的第二种实现。后来写博客的时候又现写了个brute force,来给出一个“time exceeds limit”的结果,讲真不是很必要,后面如果实现方法很简单没什么亮点就不加了吧, 简单提一下就可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值