leetcode 100 热题 三数字之和
class Solution(object):
def twoSum(self, nums,target):
rt_list=[]
myDict={}
for i ,t in enumerate(nums):
myDict[t] = i
for i ,t in enumerate(nums):
if i>0 and nums[i-1]==nums[i]:
continue
if myDict.get(target-t)!=None and myDict.get(target-t)>i:
rt_list.append([t,target-t])
return rt_list
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
rt_list=[]
nums.sort()
print(nums)
# nums_tmp=nums.deepcopy()
for i ,t in enumerate(nums):
if i>0 and nums[i-1]==nums[i]:
continue
twosum_list = self.twoSum(nums[i+1:],0 - t)
print(twosum_list)
if len(twosum_list)>0:
for sub_list in twosum_list:
sub_list.append(t)
rt_list.append(sub_list)
rt_list2=[]
for i in rt_list:
i.sort()
rt_list2.append(i)
return rt_list2
一定要重视的是不能多次对同一个元素进行处理!!!一定要有continue部分和sort部分防止出现一样的结果
原文地址:https://blog.csdn.net/chenziang1/article/details/144409708
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!