LintCode Q57 3Sum O in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月18日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
"""
@param numbersbers : Give an array numbersbers of n integer
@return : Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
# time complexity: O(n^2)
# space complexity: O(n)
numbers = sorted(numbers)
hi = len(numbers) - 1
res = set([])
for i in xrange(len(numbers)-2):
lo = i
self.searchTuplet(numbers, lo, lo + 1, hi, -numbers[lo], res)
return list(res)
def searchTuplet(self, numbers, lo, mid, hi, target, res):
# search target from position mid to hi in sorted array
# target > 0, numbers[mid] <= numbers[hi]
if numbers[hi] < 0 or numbers[mid] > target:
return
while mid < hi:
if numbers[mid] + numbers[hi] < target:
mid += 1
elif numbers[mid] + numbers[hi] > target:
hi -= 1
else: # numbers[mid] + numbers[hi] == target
res.add((numbers[lo], numbers[mid], numbers[hi]))
mid += 1
hi -= 1
return
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。