【leetcode】#15 3Sum【Array】【Medium】

7 篇文章 0 订阅

15. 3Sum

Given an array nums of n integers, are there elements abc 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]
]

题目大意

在一个数组中找到三个数a, b, c,使a + b + c = 0,且a, b, c不得重复

解题思路(待优化)

遍历数组,先确定一个数a,然后在数组中找两数相加和为-a的组合,将每三个数从小到大排序后放入set中防止重复

AC代码(待优化)

class Solution {
public:
    map<int, int> mp;
    vector<vector<int> > twoSum(vector<int>& nums, int target) {
        vector<vector<int> > rans;
        for (int j = 0; j < nums.size(); ++j) {
            vector<int> ans;
            if(mp[target - nums[j]] >= 1) {                                     //若两数相加等于target的值存在
                if(target - nums[j] == nums[j] && mp[nums[j]] == 1) continue;   //防止一个数被用两次
                ans.push_back(nums[j]);
                ans.push_back(target - nums[j]);
                rans.push_back(ans);
            }
        }
        return rans;
    }
    vector<vector<int>> threeSum(vector<int>& nums) {
        set<vector<int> > ans;
        vector<int> v;
        vector<int > positive, negative;
        for(int i = 0; i < nums.size(); i++) {
            mp[nums[i]]++;
        }
        if(mp[0] >= 3) ans.insert(vector<int>(3, 0));
        for(auto it = mp.begin(); it != mp.end(); it++) {
            if(it->first != 0 && it->second > 0) {
                vector<vector<int> > rtemp = twoSum(nums, 0 - it->first);
                for(vector<int> temp : rtemp) {
                    if(temp.size() == 2) {
                        if(it->first == temp[0] || it->first == temp[1]) {
                            if(mp[it->first] > 1) {
                                v.clear();
                                v.push_back(it->first);
                                v.insert(v.begin(), temp.begin(), temp.end());
                                sort(v.begin(), v.end());
                                ans.insert(v);
                            }
                        } else {
                            v.clear();
                            v.push_back(it->first);
                            v.insert(v.begin(), temp.begin(), temp.end());
                            sort(v.begin(), v.end());
                            ans.insert(v);
                        }
                    }
                }
            }
        }
        return vector<vector<int> >(ans.begin(), ans.end());
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值