码迷,mamicode.com
首页 > 编程语言 > 详细

[Lintcode 3sum]三数之和(python,二分)

时间:2016-06-04 16:14:26      阅读:1020      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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,二分)

标签:

原文地址:http://www.cnblogs.com/vincentX/p/5558967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!