zoukankan      html  css  js  c++  java
  • 双指针——三数之和,这种题目就是比较恶心,处理的异常情况比较多

    57. 三数之和

    中文
    English

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

    样例

    例1:

    输入:[2,7,11,15]
    输出:[]
    

    例2:

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

    注意事项

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

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

    class Solution:
        """
        @param numbers: Give an array numbers of n integer
        @return: Find all unique triplets in the array which gives the sum of zero.
        """
    
        def threeSum(self, numbers):
            # write your code here
            numbers.sort()
    
            def find_target(nums, k, target):
                l, r = k, len(nums) - 1
                ans = []
                while l < r:
                    if (r + 1 < len(nums) and nums[r] == nums[r + 1]) or 
                            (nums[l] + nums[r] > target):
                        r -= 1
                    elif (l - 1 >= k and nums[l] == nums[l - 1]) or 
                            (nums[l] + nums[r] < target):
                        l += 1
                    elif nums[l] + nums[r] == target:
                        ans.append([-target, nums[l], nums[r]])
                        r -= 1
                        l += 1
                return ans
    
            ans = []
            for i, a in enumerate(numbers):
                if a <= 0:
                    if (i > 0 and numbers[i - 1] == a):
                        continue
                    ans.extend(find_target(numbers, i + 1, -a))
    
            return ans
    
  • 相关阅读:
    jq function return value
    danci4
    danci3
    danci2
    项目总结 和语言总结。
    vm 安装 ox 10.13
    ios 异步和多线程
    ios 语法问题 全局变量。
    mvc
    object-c 之autolayout
  • 原文地址:https://www.cnblogs.com/bonelee/p/14265072.html
Copyright © 2011-2022 走看看