前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法-数组-三数之和

算法-数组-三数之和

作者头像
用户3578099
发布2022-06-10 15:49:52
5960
发布2022-06-10 15:49:52
举报
文章被收录于专栏:AI科技时讯

15.三数之和

来源:力扣(LeetCode)

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

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

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

示例 1:

代码语言:javascript
复制
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:

代码语言:javascript
复制
输入:nums = []
输出:[]

示例 3:

代码语言:javascript
复制
输入:nums = [0]
输出:[]

提示:

代码语言:javascript
复制
0 <= nums.length <= 3000
-105 <= nums[i] <= 105

解法

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

代码实现

暴力法

python实现

代码语言:javascript
复制
 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++实现

代码语言:javascript
复制
 class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        vector <vector <int>> res;
        if (n<3)
            return {};

        for (int i=0; i<n-2; i++){
            for (int j=i+1; j<n-1; j++){
                for (int k=j+1; k<n; k++){
                    if (nums[i] + nums[j] + nums[k] == 0)
                    {
                        vector<int> 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(1)
哈希表+遍历

python实现

代码语言:javascript
复制
 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++实现

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

        vector <vector <int>> res;

        for (int i=0; i<n; 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<n-1; i++){
            for (int j=i+1; j<n; 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 <int> 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<n2; k++){
                            if (it->second[k] != i && it->second[k] != j){
                                vector <int> 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)

哈希表

排序+双指针+while去重

python实现

代码语言:javascript
复制
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++实现

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

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

        for (int i=0; i<n-2; 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)

for循环+left<while循环, 排序耗时O(nlogn)

总的耗时是O(n^2)

  • 空间复杂度:O(logn)

排序消耗的空间,存储空间是O(1)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AI科技时讯 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 15.三数之和
  • 解法
  • 代码实现
    • 暴力法
      • 哈希表+遍历
        • 排序+双指针+while去重
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档