三数之和

题目描述:

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

注意事项

在三元组(a, b, c),要求a <= b <= c。

结果不能包含重复的三元组。

样例

如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:

(-1, 0, 1)

(-1, -1, 2)

解法1:三层for循环,时间复杂度O(n^3)

//解法1: O(n^3)
class Solution {
public:
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    vector<vector<int> > threeSum(vector<int> &nums) {
        // write your code here
        vector<vector<int> > ans;
        int n = nums.size();
        map<vector<int>, int> mp;
        vector<int> temp;

        for (int i=0; i<n; ++i) {
            for (int j=i+1; j<n; ++j) {
                for (int k=j+1; k<n; ++k) {
                    if (nums[i]+nums[j]+nums[k] == 0) {
                       temp.resize(0);
                       temp.push_back(nums[i]);
                       temp.push_back(nums[j]);
                       temp.push_back(nums[k]);
                       temp.resize(3);
                       sort(temp.begin(), temp.end());
                       if (mp[temp]) {
                        continue;
                       }else {
                        mp[temp]++;
                        ans.push_back(temp);
                       }
                    }
                }
            }
        }
        return ans;
    }
};

解法2:将原数组备份,遍历每一个数val,两层for循环查找是否能找到两数之和为-val。注意:三个数相等时、或任意两数相等时的情况和去重。

时间复杂度O(n^2).

//解法2:O(n^2)

class Solution {
public:
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    vector<vector<int> > threeSum(vector<int> &nums) {
        // write your code here
        vector<int> ori_num;
        map<int, int> cnt;
        for (int i=0; i<nums.size(); ++i) {
            ori_num.push_back(nums[i]);
            cnt[nums[i]]++;
        }
        vector<vector<int> > ans;
        sort(nums.begin(), nums.end());
        vector<int> temp;
        map<vector<int>, int> vector_mp;

        for (int i=0; i<nums.size(); ++i) {
            for (int j=i+1; j<nums.size(); ++j) {
                int tot = nums[i] + nums[j];
                auto iter = find(ori_num.begin(), ori_num.end(), 0-tot);
                if (nums[i] == 0-tot) {
                    if (cnt[nums[i]] < 2) continue;
                }
                if (nums[j] == 0-tot) {
                    if (cnt[nums[j]] < 2) continue;
                }
                if (nums[i] == nums[j] && nums[i] == 0-tot) {
                    if (cnt[nums[i]] < 3) continue;
                }
                if (iter != ori_num.end()) {
                    temp.resize(0);
                    temp = {0-tot, nums[i], nums[j]};
                    temp.resize(3);
                    sort(temp.begin(), temp.end());
                    if (vector_mp[temp] == 0)
                        ans.push_back(temp);
                        vector_mp[temp]++;
                }
            }
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
};

解法3:对原数组从小到大排序,从左到右遍历val,然后二分查找两个数之和是-val的。左边界i+1,右边界n-1,如果当前和=-val,加入答案,否则如果小于,左边界右移,相反右边界左移。可以利用map去重,也可以利用set容器不能包含重复项的特点来去重。时间复杂度O(nlog(n)).

/// 解法3:对原数组从小到大排序,从左到右遍历,然后找两个数之和是-target的。
class Solution {
public:
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    vector<vector<int> > threeSum(vector<int> &nums) {
        // write your code here
        sort(nums.begin(), nums.end());
        set<vector<int> > st;

        for (int i=0; i<nums.size(); ++i) {
            int val = nums[i];
            if (val > 0) break;
            int l = i + 1;
            int r = nums.size() - 1;
            while(l < r) {
                int temp = nums[l] + nums[r];
                if (temp == -val) {
                    st.insert({val, nums[l], nums[r]});
                    while(l<nums.size()-1 && nums[l+1] == nums[l]) l++;
                    while(nums[r-1] == nums[r] && r > 0) r--;
                }else if (temp > -val) r -= 1;
                else if (temp < -val) l += 1;
            }
        }
        vector<vector<int> > ans;
        set<vector<int> >::iterator iter;

        for (iter=st.begin(); iter != st.end(); ++iter) {
            ans.push_back(*iter);
        }
        return ans;
    }
};

  

时间: 2024-07-29 11:53:33

三数之和的相关文章

lintcode 中等题: 3 Sum II 三数之和II

题目 三数之和 II 给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和. 样例 例如S = [-1, 2, 1, -4] and target = 1.  和最接近1的三元组是 -1 + 2 + 1 = 2. 注意 只需要返回三元组之和,无需返回三元组本身 解题 和上一题差不多,程序也只是稍微修改了 public class Solution { /** * @param numbers: Give an array numbers of n integ

[LeetCode] 3Sum Closest 最近三数之和

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

LeetCode OJ:3Sum Closest(最接近的三数之和)

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

[LeetCode] 16. 3Sum Closest 最近三数之和

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

LeeCode数组第15题三数之和

题目:三数之和 内容: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] 思路:题目实现可分为两个步骤,分别是(1)寻找三个满足条件的元素(2)去重复对于第一个小问题,首先考虑三个for循

LeetCode(15):三数之和

Medium! 题目描述: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] 解题思路: 这道题让我们求三数之和,比之前那道Two Sum要复杂一些,考虑过先fix一个数,然后另外两个数使

leetcode 三数之和

题目: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. 题目分析: 利用循环,使得三数之和为0.分别令i,l,r为三个数,i作为外循环,遍历数组.主要难点在于不重复 参考:https://leetcode.com/problems/3sum/discuss/147561/Python-tm 代码(python): 原文地址:https://ww

LeetCode:最接近的三数之和【16】

LeetCode:最接近的三数之和[16] 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这三个数的和.假定每组输入只存在唯一答案. 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 题目分析 这道题就是三数之和问题的一种变形. 三数之和问题的求解策略是将三指针变为双指针问题

15. 三数之和(筛选数据)

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为:[ [-1, 0, 1], [-1, -1, 2]] 1/** 2 * @param {number[]} nums 3 * @return {number[][]} 4 */ 5 6var th

python三数之和

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] class Solution(object): def threeSum(self, nums): """ :type