LeetCode 15.三数之和

题目描述:

 

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

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

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

我的代码:


...不好意思没写出来,看了别人的,刚开始看不懂,后面copy到pycharm里面去一遍一遍的debug,最后终于懂了,也学习到了一些东西。
比如:(1)对数组元素进行排序,排序是为了让元素之间呈现出某种规律,处理起来会简单很多。所以,当你觉得一个似乎无从下手的问题的时候,
不妨尝试去寻找或制造一种“规律”,排序是手段之一。
   (2)可以借用c里面的一些想法,定义两个变量,把它们当成指针,这样对于一些列表问题还是很有帮助的。

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        count = len(nums)
        collect = []
        for i in range(count):
            left = i+1
            right = count-1
            #避免重复找同一个数据
            if i >0 and nums[i] == nums[i-1]:
                left +=1
                continue
            #数据按小到大排列,每次选取nums[i],在其后寻找符合a + b + c = 0的两个数据
            while left < right:
                sum = nums[i] + nums[left] + nums[right]
                if sum == 0:
                    col = [nums[i],nums[left],nums[right]]
                    collect.append(col)
                    left+=1
                    right-=1
                    #循环中nums[i]已确定,当再确定1个数时,另一个数也确定,左右端任一端出现重复均可跳过
                    while nums[left] == nums[left-1] and left < right:
                        left+=1
                    while nums[right] == nums[right+1] and left < right:
                        right-=1
                if sum<0:
                    left+=1
                elif sum > 0:
                    right-=1
        return collect          

 

 

大佬的代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_copy = nums.copy()
        nums.sort()
        front = 0
        end = len(nums) - 1
        while end>front:
            if nums[front]+nums[end]>target:
                end -=1
            elif nums[front]+nums[end]<target:
                front+=1
            else:
                first = nums_copy.index(nums[front])
                #如果first和second相等,可能会找到同一个序号,所以设置为None
                nums_copy[first] = None
                second = nums_copy.index(nums[end])
                return first,second

三数之和耗时最短的代码利用了除0以外正负数相加才会等于零的关系,划分正负数,按条件选取;用好数学关系确实能使代码高效不少。(别人说的)

posted @ 2019-03-20 22:06  阿笑笑君  阅读(117)  评论(0编辑  收藏  举报