栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leetcode:15.三数之和

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode:15.三数之和

15.三数之和

来源:力扣(LeetCode)

链接: https://leetcode.cn/problems/3sum

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:

输入:nums = []
输出:[]

示例 3:

输入:nums = [0]
输出:[]

提示:

0 <= nums.length <= 3000
-105 <= nums[i] <= 105
解法
  • 暴力法:没有思路的时候就暴力解法,三重循环,找满足条件的情况;
  • 遍历+哈希表:双重循环,边查看target减去两个元素的差值是否在哈希表内,如果在,返回结果,如果不在,将该元素入哈希表,空间换时间;
  • 排序+双指针+while去重:由于要去重,可以考虑排序后就能避免相邻元素相同导致重复结果,for循环遍历的时候,left指针是该元素右边的第一个元素,right指针是末尾元素,开始判断三个元素和与0的关系,如果相等存入结果,左右指针加一减一操作。这里注意三个元素都要考虑相邻去重的问题,起始元素直接在开头就判断去重,另外如果起始元素大于0直接break掉循环,后面的left指针 right指针在进行加一减一操作后也要判断去重,直接用while循环比较与之前状态是否相等即可
代码实现 暴力法

python实现

 class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # 暴力,三重循环
        n = len(nums)
        if n < 3:
            return []
        res = []
        for i in range(n-2):
            for j in range(i+1, n-1):
                for k in range(j+1, n):
                    if nums[i] + nums[j] + nums[k] == 0:
                        if sorted([nums[i], nums[j], nums[k]]) not in res:
                            res.append(sorted([nums[i], nums[j], nums[k]]))
        return res

c++实现

 class Solution {
public:
    vector> threeSum(vector& nums) {
        int n = nums.size();
        vector > res;
        if (n<3)
            return {};

        for (int i=0; i
            for (int j=i+1; j
                for (int k=j+1; k
                    if (nums[i] + nums[j] + nums[k] == 0)
                    {
                        vector inner_res = {nums[i], nums[j], nums[k]};
                        sort(inner_res.begin(), inner_res.end());
                        if (find(res.begin(), res.end(), inner_res) == res.end()){
                            res.push_back(inner_res);
                        }
                    }
                }
            }
        }
        return res;

    }
};

复杂度分析

  • 时间复杂度: O ( n 3 ) O(n^3) O(n3) 排序虽然也花时间,但可以忽略不计
  • 空间复杂度: O ( 1 ) O(1) O(1)
哈希表+遍历

python实现

 class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # 转换为两数之和 利用并利用哈希表的方法
        n = len(nums)
        hashTable = dict()
        res = []
        if n < 3:
            return res
        for i in range(n):
            if nums[i] in hashTable:
                hashTable[nums[i]].append(i)
            else:
                hashTable[nums[i]] = [i]
        for i in range(n-1):
            for j in range(i+1, n):
                diff = 0 - nums[i] - nums[j]
                if diff in hashTable:
                    # 这个地方要判断是否有重复元素
                    diff_index = hashTable[diff]
                    if len(diff_index) == 1 and diff_index[0] not in [i, j]:
                        inner_res = sorted([nums[i], nums[j], diff])
                        if inner_res not in res:
                            res.append(inner_res)
                    elif len(diff_index) > 1:
                        for index in diff_index:
                            if index not in [i, j]:
                                inner_res = sorted([nums[i], nums[j], nums[index]])
                                if inner_res not in res:
                                    res.append(inner_res)
        return res

c++实现

 class Solution {
public:
    vector> threeSum(vector& nums) {
        // 两层循环+哈希表
        int n = nums.size();
        unordered_map > hashTabel;
        if (n<3){
            return {};
        }

        vector > res;

        for (int i=0; i
            auto it = hashTabel.find(nums[i]);
            if (it != hashTabel.end()){
                // find
                hashTabel[nums[i]].push_back(i);
            }
            else{
                hashTabel[nums[i]] = {i};
            }
        }

        for (int i=0; i
            for (int j=i+1; j
                int diff = 0 - nums[i] - nums[j];

                auto it = hashTabel.find(diff);

                if (it != hashTabel.end()){
                    if (it->second.size() == 1){
                        int index = it->second.front();
                        if(index != i && index != j){
                            vector  inner_res = {nums[i], nums[j], diff};
                            sort(inner_res.begin(), inner_res.end());
                            auto it2 = find(res.begin(), res.end(), inner_res);
                            if(it2 == res.end()){
                                res.push_back(inner_res);
                            }
                        }
                    }
                    else if (it->second.size() > 1){
                        int n2 = it->second.size();
                        for (int k=0; k
                            if (it->second[k] != i && it->second[k] != j){
                                vector  inner_res = {nums[i], nums[j], nums[it->second[k]]};
                                sort(inner_res.begin(), inner_res.end());
                                auto it2 = find(res.begin(), res.end(), inner_res);
                                if (it2 == res.end()){
                                    res.push_back(inner_res);
                                }
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
};

复杂度分析

  • 时间复杂度: O ( n 3 ) O(n^3) O(n3) 两重循环+哈希表元素中的遍历循环
  • 空间复杂度: O ( n ) O(n) O(n) 哈希表
排序+双指针+while去重

python实现

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # 排序 + 双指针 + 三数判相邻元素重复
        n = len(nums)
        if n < 3:
            return []
        
        nums.sort()
        res = []
        for index in range(n-2):
            if nums[index] > 0:
                break
            if index > 0 and nums[index] == nums[index-1]:
                continue
            
            left = index + 1
            right = n - 1

            while left < right:
                if nums[index] + nums[left] + nums[right] == 0:
                    res.append([nums[index], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while nums[left] == nums[left-1] and left < right:
                        left += 1
                    while nums[right] == nums[right+1] and left < right:
                        right -= 1
                elif nums[index] + nums[left] + nums[right] > 0:
                    # right -> move left
                    right -= 1
                elif nums[index] + nums[left] + nums[right] < 0:
                    # left -> move right
                    left += 1
        return res

c++实现

class Solution {
public:
    vector> threeSum(vector& nums) {
        // 排序加左右双指针+while去重
        int n = nums.size();
        if (n<3){
            return {};
        }
        vector > res;

        sort(nums.begin(), nums.end());

        for (int i=0; i
            if (nums[i] > 0){
                break;
            }

            if (i>0 && nums[i] == nums[i-1]){
                continue;
            }

            int left = i + 1;
            int right = n - 1;
            while (left < right){
                if (nums[i] + nums[left] + nums[right] == 0){
                    res.push_back({nums[i], nums[left], nums[right]});
                    left++;
                    right--;
                    while (nums[left] == nums[left-1] && left < right){
                        left++;
                    }
                    while (nums[right] == nums[right+1] && left < right){
                        right--;
                    }
                }
                else if (nums[i] + nums[left] + nums[right] > 0){
                    right--;
                }
                else {
                    left++;
                }
            }
        }
        return res;
    }
};

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2) for循环+left
  • 空间复杂度: O ( l o g n ) O(logn) O(logn) 排序消耗的空间,存储空间是O(1)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号