• 【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

  • 相关阅读:
    Oracle重建表索引及手工收集统计信息
    VirtualBox虚拟机安装MSDOS和MINIX2.0.0双系统
    odp.net以及oracle oledb安装
    Oralce常用维护命令
    Sales_item
    IBM MQ Reason 2538(MQRC_HOST_NOT_AVAILABLE) 错误原因一例
    Unable to create the store directory. (Exception from HRESULT: 0x80131468)
    WMS函数组:13.WMS入库BAPI
    WMS函数组:12.批量入库物料移动凭证
    WMS函数组:11.交货单取金额
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10641709.html
Copyright © 2020-2023  润新知