leetcode-mid-array-31 three sum-NO
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
leetcode-mid-array-31 three sum-NO的更多相关文章
- [LeetCode] Split Array with Equal Sum 分割数组成和相同的子数组
Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies fol ...
- Leetcode: Split Array Largest Sum
Given an array which consists of non-negative integers and an integer m, you can split the array int ...
- [LeetCode] Split Array With Same Average 分割数组成相同平均值的小数组
In a given integer array A, we must move every element of A to either list B or list C. (B and C ini ...
- leetcode 数组array
120. Triangle 给出一个三角形(数据数组),找出从上往下的最小路径和.每一步只能移动到下一行中的相邻结点上. 解法,自底向上 The idea is simple. Go from bot ...
- [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- C++ STL@ list 应用 (leetcode: Rotate Array)
STL中的list就是一双向链表,可高效地进行插入删除元素. List 是 C++标准程式库 中的一个 类 ,可以简单视之为双向 连结串行 ,以线性列的方式管理物件集合.list 的特色是在集合的任何 ...
- [leetcode]364. Nested List Weight Sum II嵌套列表加权和II
Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)
Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...
- LeetCode(113) Path Sum II
题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...
随机推荐
- JDBC插入中文数据出现?号地解决问题
1. 查看jdbc配置是否指定编码 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/te ...
- 洛谷P2507 [SCOI2008]配对 题解(dp+贪心)
洛谷P2507 [SCOI2008]配对 题解(dp+贪心) 标签:题解 阅读体验:https://zybuluo.com/Junlier/note/1299251 链接题目地址:洛谷P2507 [S ...
- UML类图(一)
前言 最近在学习程杰老师的<大话设计模式>,觉得非常不错,就做了一些学习笔记和总结.如果对设计模式很感兴趣的,可以直接阅读书籍,相信会有更多的收获. 本人小菜一枚,如果理解的不对的还请多多 ...
- Python 入门之常用运算符
Python 入门之常用运算符 Python中的运算按种类可分为算数运算.比较运算.逻辑运算.赋值运算.成员运算.身份运算.位运算 1.常用运算符: (1)算数运算符: + - * / %(取余(模) ...
- [LOJ 6253] Yazid 的新生舞会
link $solution:$ 不知道为什么别人的代码能写的非常短,难道就是写差分的好处? 这种题肯定是算每个众数的贡献,考虑通过暴力众数求出个数. 现在考虑众数 $x$ ,则在序列 $a$ 中将等 ...
- vue eslint 规范配置
vue eslint 规范配置 为了代码格式统一,避免一些低级或者不合理的错误,现强行使用eslint的 standard规范 项目配置 目前都是使用 vue 提供的脚手架进行开发的,虽然 vue-c ...
- Ruby下安装cocoapods
常规安装:(文末:特殊安装) 注: 1.Mac OS X EI Capitan 10.11中需要更改安装路劲: sudo gem install -n /usr/local/bin cocoapods ...
- i3wm 配置刷新生效 和 使用mod快捷打开 ranger 小贴士
在某处学习到了如何配置i3wm后,对其极感兴趣. 学习到的经验总结: Linux中的各种命令操作其实都要首先查阅 man command 或者 command -h 或者 command -- ...
- Mongo--03 mongo副本集、备份与恢复
目录 一.mongo副本集配置 二.查看副本集状态 三.副本集权重调整 四.创建节点 五.仲裁节点 六.mongo备份与恢复 七.准备测试数据 一.mongo副本集配置 1.创建节点目录和数据目录 # ...
- oracle 主键自增并获取自增id
1 创建表 /*第一步:创建表格*/ create table t_user( id int primary key, --主键,自增长 username varchar(20), password ...