[LeetCode][Python]15:3Sum

# -*- coding: utf8 -*-‘‘‘__author__ = ‘[email protected]‘

15: 3Sumhttps://oj.leetcode.com/problems/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:Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)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)

===Comments by Dabay===先排序,然后从左到右固定一个数,在后边的数列中使用左右指针往中间靠拢的方法查找。

从左往右固定一个数(如果需要判断的数与之前的相等就跳过),左右两个指针往中间靠拢的时候,能够保证不遗漏。(如果找到一组数据之后,左指针继续移动到下一个数不相等的数)‘‘‘class Solution:    # @return a list of lists of length 3, [[val1,val2,val3]]    def threeSum(self, num):        if len(num) < 3:            return []        num.sort()        res = []        for i in xrange(len(num)-2):            if i>0 and num[i]==num[i-1]:                continue            target = 0 - num[i]            j, k = i+1, len(num)-1            while j < k:                if num[j] + num[k] == target:                    res.append([num[i], num[j], num[k]])                    j = j + 1                    while j<k and num[j]==num[j-1]:                        j = j + 1                elif num[j] + num[k] < target:                    j = j + 1                else:                    k = k - 1        return res

def main():    sol = Solution()    nums = [0,0,0,0,0]    solutions = sol.threeSum(nums)    for solution in solutions:        print solution

if __name__ == "__main__":    import time    start = time.clock()    main()    print "%s sec" % (time.clock() - start)
时间: 2024-10-23 20:21:55

[LeetCode][Python]15:3Sum的相关文章

leetcode第15题--3Sum

Problem: 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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)

LeetCode(15) 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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The so

[LeetCode]题解(python):015-3Sum

题目来源: https://leetcode.com/problems/3sum/ 题意分析: 这道题目是输入一个数组nums.找出所有的3个数使得这3个数之和为0.要求1.输出的3个数按小到大排序,2.3个数的组合不重复.比如输入[-1,0,1,2,-1,-4],返回的应该是[[-1,0,1],[-1,-1,2]]. 题目思路: 如果直接暴力解决,那么时间复杂度是(O(n^3)).这样会TLE. 看到这道题目,我回想了leetcode的第一题.第一题是给出一个数组和一个target,找出数组的

[LeetCode]题解(python):016-3Sum Closest

题目来源: https://leetcode.com/problems/3sum-closest/ 题意分析: 这道题目输入一个数组nums和一个数target,找出数组中三个数,使得他们的和最接近target,返回这三个数的和. 题目思路: 这道题目和上一题3Sum很像,所以也可以用类似的方法去解决这个问题.整个过程分成两步: ①数组排序:这步时间复杂度是(O(nlogn)). ②固定一个数,这步的时间复杂度是(O(n)). ③在剩下的数里面通过“夹逼定理”,找出两个数,使得三个数的和最接近t

[LeetCode]题解(python):029-Divide Two Integers

题目来源: https://leetcode.com/problems/divide-two-integers/ 题意分析: 不用乘法,除法和mod运算来实现一个除法.如果数值超过了int类型那么返回int的最大值. 题目思路: 初步来说,有两个做法. ①模拟除法的过程,从高位开始除,不够先右挪一位.这种方法首先要将每一位的数字都先拿出来,由于最大int类型,所以输入的长度不超过12位.接下来就是模拟除法的过程. ②利用左移操作来实现出发过程.将一个数左移等于将一个数×2,取一个tmp = di

[LeetCode]题解(python):131-Palindrome Partitioning

题目来源: https://leetcode.com/problems/palindrome-partitioning/ 题意分析: 给定一个字符串s,将s拆成若干个子字符串,使得所有的子字符串都是回文字符串,返回所有这样的子字符串集合.比如s = “aab”,那么返回[["aa","b"],["a","a","b"]]. 题目思路: 这是一个动态规划问题,如果s[:i]是回文字符串,那么s[:i] X s

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

[LeetCode]题解(python):036-Valid Sudoku

题目来源: https://leetcode.com/problems/valid-sudoku/ 题意分析: 判断一个数独是不是可以满足规则的,也就是列行和小九宫格都是包括有且仅有1到9. 题目思路: 刚开始看这个题目的时候觉得就是要先把数独给填好,可以填好就是true的,否者就是false.不过这只是一个easy难度的题目,不可能要这么做吧.然后我测试了一些数据,发现[".87654321","2........","3........",&

[LeetCode]题解(python):037-Sudoku Solver

题目来源: https://leetcode.com/problems/sudoku-solver/ 题意分析: 这次的题目就是上一题的进化版.填好一个数独. 题目思路: 这题直接用dfs暴力解决.把“*”用(1-9)直接填就行.时间复杂度比较高.要注意的是,题目要求没有返回值,所以要另外写一个函数用来判断填数之后是否满足可以填好. 代码(python): 1 class Solution(object): 2 def isValue(self,board,x,y): 3 #列符合 4 for