-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_3sum.py
69 lines (56 loc) · 1.93 KB
/
linear_3sum.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import json
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
candidates = []
sorted_nums = sorted(nums)
for i in range(len(sorted_nums)):
if i == 0 or (sorted_nums[i] != sorted_nums[i-1]):
k1 = sorted_nums[i] # first number
head = i+1
tail = len(sorted_nums)-1
while head < tail: # find second and third
if sorted_nums[head]+sorted_nums[tail]==-k1:
k2 = sorted_nums[head]
k3 = sorted_nums[tail]
candidates.append([k1,k2,k3])
while head < tail and sorted_nums[head+1]==sorted_nums[head]:
head += 1
while head < tail and sorted_nums[tail-1]==sorted_nums[tail]:
tail -= 1
head += 1
tail -= 1
else:
if sorted_nums[head]+sorted_nums[tail]<-k1:
head += 1
else:
tail -= 1
return candidates
def stringToIntegerList(input):
return json.loads(input)
def int2dArrayToString(input):
return json.dumps(input)
def stringToIntegerList(input):
return json.loads(input)
def int2dArrayToString(input):
return json.dumps(input)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
nums = stringToIntegerList(line)
ret = Solution().threeSum(nums)
out = int2dArrayToString(ret)
print out
except StopIteration:
break
if __name__ == '__main__':
main()