zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】3Sum(三数之和)

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

    思路


      我们先对数组进行排序,然后从第一个数字开始查找, 然后在后面的数组中查找是否有满足条件的(使用两个指针一个指向开头,一个指向尾部开始遍历)。时间复杂度为O(n*n), 空间复杂度为O(1)。

    图示步骤

            

    解决代码


     1 class Solution(object):
     2     def threeSum(self, nums):
     3         nums.sort()
     4         length = len(nums) 
     5         res_list = []
     6         for i in range(length - 2):                  # 以此下标的数字和其他进行匹配
     7             if i > 0 and nums[i] == nums[i - 1]:      # 如果和上一个数字相等,直接返回。 因为上一次已经查找过
     8                 continue
     9             start, end = i + 1, length-1             # 在后面的数组中设置起始指针和尾部指针
    10             while start < end:                       
    11                 tem = nums[i] + nums[start] + nums[end]
    12                 if tem == 0:                                 # 如果三个数字之和等于0,将其进行添加
    13                     res_list.append([nums[i], nums[start], nums[end]])          
    14                    
    15                     while start < end and nums[start] == nums[start+1]:    # 判断start下一个数字和当前数字是否相等,相等下移一位。不然会添加进重复的元素
    16                         start += 1                                          
    17                     while start < end and nums[end] == nums[end-1]:          # 判断end上一个数字和当前数字是否相等,相等则跳过。
    18                         end -= 1
    19                     start += 1
    20                     end -= 1
    21                 elif tem < 0:                                           # 和小于 0 的话,start进位
    22                     start += 1
    23                 else:                                                   # 和大于0的话,end减一
    24                     end -= 1
    25         return res_list

  • 相关阅读:
    HDU 5795
    HDU5783
    HDU 5791
    VK Cup 2016
    Codeforces Round #357 (Div. 2)
    Educational Codeforces Round 15
    HDU5724
    博弈学习 3
    Spring的多配置文件加载
    spring 核心技术
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10641709.html
Copyright © 2011-2022 走看看