美文网首页
leetcode15. 三数之和

leetcode15. 三数之和

作者: 冰源 | 来源:发表于2018-09-17 23:05 被阅读3次
给定一个包含 n 个整数的数组 nums,
判断 nums 中是否存在三个元素 a,b,c ,
使得 a + b + c = 0 ?
找出`所有`满足条件且不重复的三元组。
注意:答案中`不可以包含重复`的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
//cpp
/*
3SUM:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 
Find all unique triplets in the array which gives the sum of zero.
*/

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int length = nums.size();
        vector<vector<int>> result;

        //对数组nums进行快速排序
        sort(nums.begin(), nums.end());

        if(length > 0 && nums[length-1] < 0) return result; 

        for (int i = 0; i < length - 1; i++) 
        {
            // if nums[i] > 0, we can never get sum to 0
            if(nums[i] > 0) break;
            
            //avoid duplicate triplets
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            
            int target = -nums[i];
            int left = i + 1, right = length - 1;
            // both side
            while (left < right) 
            {
                // target is negative
                if (nums[left] + nums[right] > target)
                {
                    // right side is too huge
                    right--;
                } 
                else if (nums[left] + nums[right] < target) 
                {
                    // left side is too small
                    left++;
                }
                else 
                {
                    result.push_back({nums[i],nums[left],nums[right]});
                    while (++left < right && nums[left] == nums[left - 1]) ;
                    while (--right > left && nums[right] == nums[right + 1]) ;
                }
            }
        }
        return result;
    }
};
#python
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) < 3:
            return []
        nums.sort()
        res = set()
        for i, v in enumerate(nums[:-2]):
            if i >= 1 and v == nums[i-1]:
                continue
            d = {}
            for x in nums[i+1:]:
                if x not in d:
                    d[-v-x] = 1  #因为排序的原因,a<=b<=c,c=-(a+b)一定在a/b后面;d[-v-x]就是寻找c。
                else:
                    res.add((v, -v-x, x))
        return list(map(list, res))
#python更加详细解释
class Solution(object):
    def threeSum(self, nums):
        nums.sort()
        res = []
        for idx,val in enumerate(nums):
            if idx>=1 and val == nums[idx-1]:
                continue
            # 思想:有没有人正在找我?没有的话,我就去找我想找的人。
            wanted_pairs = {} # 想找的人
            temp=None
            for pair in nums[idx+1:]:
                if pair==temp:
                    continue
                if pair not in wanted_pairs: # Not他们想找的人,then加入他们去找我想找的人
                    wanted_pairs[0 - val - pair]=1
                else:
                    res.append([val,pair,0 - val - pair]) # 我就是他们中那个谁想找的人
                    temp=pair
        return res

相关文章

  • LeetCode15.三数之和 JavaScript

    LeetCode15.三数之和 JavaScript 给定一个包含n个整数的数组 nums,判断 nums中是否存...

  • leetcode15. 三数之和

  • LeetCode15. 三数之和

    题目 15. 三数之和 题目描述 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a...

  • leetcode15.三数之和

    题目链接 排序+双指针夹逼法 对于本题,无论是暴力求解,还是使用哈希表求解,我觉得都不如排序之后使用左右夹逼的方法...

  • leetcode15. 三数之和 python实现

    题目: 解法: 先对数组从小到大排序。 最外层遍历整个数组,再设置两个双指针,当三数之和小于0时,右指针向左移动一...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • LeetCode 第18题:四数之和

    1、前言 2、思路 采用三数之和的思路,原本三数之和可以分解为:数组中的一个数 + 此数右边的数求两数之和,那么四...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

  • 两数之和,三数之和

    转载:https://www.cnblogs.com/DarrenChan/p/8871495.html 1. 两...

  • 双指针总结

    左右指针 主要解决数组中的问题:如二分查找 盛最多水的容器 三数之和 四数之和 最接近三数之和 快慢指针 主要解决...

网友评论

      本文标题:leetcode15. 三数之和

      本文链接:https://www.haomeiwen.com/subject/ecllnftx.html