查找表_leetcode15

#coding=utf-8
# 解题思路:查找表 n2 20190302 找工作期间
# 排序数组的双指针求和法 : (0,n) -> (a,b)
# 其中a只能增加 b只能减少 : 搜索方向的问题 ,不然会到重复的状态

class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# 时间复杂度 n3
if len(nums) < 3:
return []
result = []
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
sum = nums[i] + nums[j]
if -sum in nums:
k = nums.index(-sum)
if k != i and k != j:
temp = sorted([nums[i], nums[j], nums[k]])
if temp not in result:
result.append(temp)
return result



class Solution2(object):
def threeSum(self, nums):
if len(nums) < 3:
return []
result = []
nums = sorted(nums)
for index, item in enumerate(nums):
target = -item
start = index + 1
end = len(nums) - 1
if item > 0 or nums[end] < 0:
break
if index > 0 and item == nums[index-1]:
continue
while start < end:
if nums[end] < 0:
break
if nums[start] + nums[end] == target:
temp_list = [nums[index], nums[start], nums[end]]
result.append(temp_list)

while start < end and nums[start] == nums[start+1]:
start = start + 1
while start < end and nums[end] == nums[end-1]:
end = end - 1

start = start + 1
end = end - 1

elif nums[start] + nums[end] < target:
start = start + 1
else:
end = end - 1

return result
posted @ 2019-03-17 14:29  AceKo  阅读(128)  评论(0编辑  收藏  举报