[Leetcode][python/java]3Sum

题目大意

从一个数组中找到三个数,使这三个数的和为0。有可能存在多组解,也有可能存在重复的解,所以需要去重。比如:num=[-1,0,1,2,-1,-4];那么存在两组解:[[-1,0,1],[-1,-1,2]],解中的数需要是从小到大排序状态。

解题思路

启发自:博客
1 先将数组排序。
2 排序后,可以按照TwoSum的思路来解题。怎么解呢?可以将num[i]的相反数即-num[i]作为target,然后从i+1到len(num)-1的数组元素中寻找两个数使它们的和为-num[i]就可以了。
3 这个过程要注意去重。

Python

使用哈希+双指针

这个解法是自己写的,主要是由于直接双指针python过不了,所以用了twosum的哈希解法,然后发现依然超时,因为直接在res这个list上去重还是有很大复杂度,所以只能用dict存储,key为字符串,value为list,最后终于过了,超过91%。
discussion的很多和这个类似

时间复杂度:O(n^2),假设hash是O(1)的话。

class Solution:
    def twoSum(self, nums, target):
        idxDict = dict()
        idx_list = []
        for idx, num in enumerate(nums):
            if target - num in idxDict:
                idx_list.append([idxDict[target - num], idx])
            idxDict[num] = idx
        return idx_list

    def threeSum(self, num):
        num.sort()
        res = dict()
        result = []
        for i in range(len(num)-2):  # 遍历至倒数第三个,后面两个指针
            if (i == 0 or num[i] > num[i-1]) and num[i] <= 0:  # 只检索不重复并且目标数(第一个数)小于等于0的情况
                left = i + 1; 
                # right = len(num) - 1
                result_idx = self.twoSum(num[left:], -num[i])
                for each_idx in result_idx:  # 数组后方切片后给twoSum
                    each_result = [num[i], num[each_idx[0]+(i+1)], num[each_idx[1]+(i+1)]]
                    if str(each_result) not in res:
                        res[str(each_result)] = each_result
        for value in res.values():
            result.append(value)
        return result    

双指针

超时
时间复杂度:O(N^2)+O(N) = O(N^2),但显然比上面一种解法复杂度更高,不然也不会GG。

class Solution:
    def threeSum(self, num):
        num.sort()
        res = []
        for i in range(len(num)-2):  # 遍历至倒数第三个,后面两个指针
            if i == 0 or num[i] > num[i-1]:
                left = i + 1
                right = len(num) - 1
                while left < right:  # 值得注意的是,这里左右指针将这个数所有情况都遍历加入,所以遇到同样的数直接跳过
                    if num[left] + num[right] == -num[i]:
                        res.append([num[i], num[left], num[right]])
                        left += 1; right -= 1
                        while left < right and num[left] == num[left-1]: left +=1
                        while left < right and num[right] == num[right+1]: right -= 1
                    elif num[left] + num[right] < -num[i]:
                        while left < right:
                            left += 1
                            if num[left] > num[left-1]: break
                    else:
                        while left < right:
                            right -= 1
                            if num[right] < num[right+1]: break
        return res

Java

双指针

时间复杂度:O(N^2)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        int i = 0;
        while (i < nums.length - 2) {
            if (nums[i] > 0) break;
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    list.add(Arrays.asList(nums[i], nums[left++], nums[right--]));
                    while (left < right && nums[left] == nums[left - 1]) ++left;
                    while (left < right && nums[right] == nums[right + 1]) --right;
                } else if (sum < 0) ++left;
                else --right; // ++写在前面,说明++先有效,即b要+1,然后赋值给a
            }
            while (nums[i] == nums[++i] && i < nums.length - 2) ;  // 如果数字重复跳过遍历
        }
        return list;
    }
}

总结

in 操作符在 dict 里面可以理解为是 O(1) 的时间复杂度,在 list 里面可以理解为是 O(n)。

用双指针是可行的,只是去重手法不好会超时而已。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值