[Lintcode 3sum]三数之和(python,二分)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode 3sum]三数之和(python,二分)相关的知识,希望对你有一定的参考价值。
题目链接:http://www.lintcode.com/zh-cn/problem/3sum/?rand=true#
用这个OJ练练python…这个题意和解法就不多说了,O(n^2lgn)就行了,关键是!!python的语法…
要想给tuple排序,如果直接sort的话会自动转成list,这个时候要再转回来。
1 class Solution: 2 """ 3 @param numbersbers : Give an array numbersbers of n integer 4 @return : Find all unique triplets in the array which gives the sum of zero. 5 """ 6 def Solution(self): 7 pass 8 def threeSum(self, numbers): 9 # write your code here 10 numbers.sort() 11 ret = [] 12 n = len(numbers) 13 for i in range(0, n): 14 for j in range(i+1, n): 15 d = -(numbers[j] + numbers[i]) 16 l = 0 17 r = n - 1 18 p = -1 19 while l <= r: 20 m = (l + r) >> 1 21 if numbers[m] == d: 22 p = m 23 break 24 elif numbers[m] > d: 25 r = m - 1 26 elif numbers[m] < d: 27 l = m + 1 28 if p != -1 and p != i and p != j: 29 ret.append((numbers[i], numbers[j], numbers[p])) 30 nn = len(ret) 31 for i in range(0, nn): 32 ret[i] = list(ret[i]) 33 ret[i].sort() 34 ret[i] = tuple(ret[i]) 35 ret = list(set(ret)) 36 return ret
以上是关于[Lintcode 3sum]三数之和(python,二分)的主要内容,如果未能解决你的问题,请参考以下文章