zoukankan      html  css  js  c++  java
  • LeetCode: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.
    Note: The solution set must not contain duplicate triplets.

    For example, given array S = [-1, 0, 1, 2, -1, -4],
    A solution set is:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    思路

    暴力的话,时间复杂度是O(n3),试了下,肯定不行的,我开始想能不能转换2sum,就是先遍历一遍,求出两个数之和,然后再找这两个数之和存不存在就行。提交了一下,时间上还是过不了,想了半天,就只能用排序的方法,这样的话,我只需要从最左和最右开始找,有点二分的味道。这样的话,最坏情况是O(n2)。

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            length = len(nums)
            nums.sort() #排序
            last = length
            result = []
            for i in range(length - 2):
                if(i > 0 and nums[i-1] == nums[i]):
                    continue #如果i和上次重复了,那么就不用找了!
                l,r = i+1,length-1
                flag = True
                while(l < r):
                    s = nums[i] + nums[l] + nums[r]
                    if s < 0:
                        l += 1
                    elif s > 0:
                        r -= 1
                    else:
                        result.append([nums[i],nums[l],nums[r]])
                        while(l < r and nums[l] == nums[l+1]):
                            l += 1
                        while(l < r and nums[r] == nums[r-1]):
                            r -= 1
                        l += 1
                        r -= 1
            return result
    
  • 相关阅读:
    外部排序
    oceanbase tpcc 关键总结
    TPCC测试
    最简单的oracle 19c安装教程
    unix进程环境
    tars以docker方式安装
    异常安全的赋值运算符函数
    linux 定时器setitimer使用
    libevent学习-reactor设计模式及代码示例
    linux中可执行程序搜索动态链接库的顺序
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/8447967.html
Copyright © 2011-2022 走看看