leetcode-mid-array-31 three sum-NO
2024-09-05 21:50:45
my code: time limited
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def twoSum(a,b,c):
if a + b + c == 0:
return True
else:
return False res = []
for i in range(len(nums)-2):
a = nums[i]
for j in range(i+1,len(nums)-1):
b = nums[j]
k = j +1
#print(i,j,k,a,b,nums[k])
while k < len(nums):
print(a,b,nums[k])
if twoSum(a,b,nums[k]) :
print('....',a,b,nums[k])
temp = [a,b,nums[k]]
temp.sort()
print('...temp',temp)
if temp not in res:
res.append(temp)
print('....res',res)
k += 1
return res
思路:
1、时间复杂度n*n
排序 ( WT1:为什么要排序?)-》构建字典记录value:次数-》两层循环,其中不断不判断第三个数是不是也等于两层循环的值(用到dic的记录次数)
class Solution(object): '''
O(n^2)时间复杂度 '''
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
num_cnt_dict = {} for num in nums:
num_cnt_dict[num] = num_cnt_dict.get(num, 0) + 1 if 0 in num_cnt_dict and num_cnt_dict[0] >= 3:
result.append([0, 0, 0]) nums = sorted(list(num_cnt_dict.keys())) for i, num in enumerate(nums):
for j in nums[i+1:]:
if num * 2 + j == 0 and num_cnt_dict[num] >=2:
result.append([num, num, j])
if j * 2 + num == 0 and num_cnt_dict[j] >= 2:
result.append([j, j, num]) diff = 0 - num - j
if diff > j and diff in num_cnt_dict:
result.append([num, j, diff])
return result
注意,以下的方式就会超时,可能是因为list和dict.keys()的检索查找方式不同
if diff > b and diff in nums: #要注意>b,才能不和前面的if重合
res.append([a,b,diff])
return res
2、n*m 其中n+m=len(nums)
构建dict -》 不排序,将dic的keys分为正数和负数-》两层for循环
注意下面这一行:是因为filter得到的是有序递增数列!!!!!!!所以当diff小于a时,说明当i=diff时候,由于不满足这个条件,还没有把[a,b,diff]放入最后结果
if diff<a or diff>b:
res.append([a,b,diff])
class Solution(object): '''
O(n^2)时间复杂度 '''
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
dic = {}
for item in nums:
dic[item] = dic.get(item,0) + 1
if 0 in dic and dic[0] >= 3:
res.append([0,0,0]) #为什么这个要单独列出来 -》因为除了这种情况,for循环中不会再出现三个数相等且和为0的情况
#nums = sorted(list(dic.keys()))
neg = list(filter(lambda x:x<0,dic.keys()))
pos = list(filter(lambda x:x>=0,dic.keys()))
for a in neg:
for b in pos:#为什么j的有边界不是len(nums)-1 -》因为可能会存在第三个数巧合和nums[j]相等
diff = 0 - a - b
if diff in dic:
if diff in (a,b) and dic[diff] >= 2:
res.append([a,b,diff])
if diff<a or diff>b:
res.append([a,b,diff])
return res
最新文章
- (IOS)BaiduFM 程序分析
- 5.3 Static
- Centos Ping不通外网
- ansible 小试身手
- 4.django笔记之admin
- 【C#学习笔记】浏览目录得到路径
- cocos2d-x结合cocosbuilder,不同屏幕适配小结
- 任务分配book
- Markdown公式编辑
- javascript中的null,对象系统还是非对象系统?
- C语言Linix服务器网络爬虫项目(二)项目设计和通过一个http请求抓取网页的简单实现
- java中throw与throws
- eslint常用关闭校验语句
- AS 常用快捷键
- mvc 之 学习地址
- 【Java】模拟Sping,实现其IOC和AOP核心(一)
- Linux内核第五节 20135332武西垚
- 前端之Bootstrap框架
- 【SPL标准库专题(1)】 SPL简介
- 插入排序的C、C++实现