LeetCode 第15题-三数之和
1. 题目
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
2. 思路
这道题最直接想到的应该是两数之和,两数之和还是比较基础的,采用通知记录的方式,维护一个字典,看新的数是否属于这个字典的键即可。三数之和也可以使用类似的办法,但是题目要求的是不能有重复的,这就比较难办了,那可能只有先将其排序,然后判断一下他们是否在集合中,思路就显而意见了,代码如下:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
for i,j in enumerate(nums):
temp = nums[:i]+nums[i+1:]
dic1 = {}
dic2 = {}
for count,k in enumerate(temp):
if k not in dic1:
dic1[-j-k] = k
else:
dic2[tuple(sorted([j,k,-j-k]))] = [j,k,-j-k]
return dic2.values()
3. 改进
然而不幸的是,这个复杂度太高,跑不过所有case便会超时,在这之前我使用的是判断list是否在list中,这样的话更没有办法通过所有的case,复杂度太高,优化以后使用字典但还是在全是0的case失败了。
经过修改后和一些边界条件,给出一个通过了case,但是极其慢的解法,我称其为无情解法:
def threeSum(self, nums: List[int]) -> List[List[int]]:
dic2 = {}
if (len(set(nums) ) == 1)and (len(nums) > 2): #主要是去除全是0 的情况,全是0 就会导致最后的循环复杂度过高
if 0 in set(nums):
return [[0,0,0]]
for i,j in enumerate(nums):
temp = nums[:i]+nums[i+1:]
dic1 = {}
for count,k in enumerate(temp):
if k not in dic1:
dic1[-j-k] = k
else:
dic2[tuple(sorted([j,k,-j-k]))] = [j,k,-j-k]
return dic2.values()
下面给出正确的解法,使用双指针
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
res = []
dic1 = {}
for i,j in enumerate(nums):
if j > 0:
continue
temp = nums[i+1:]
left = 0
right = len(temp)-1
while(left < right): if j + temp[left]+temp[right] == 0:
dic1[(j,temp[left],temp[right])] = [j,temp[left],temp[right]]
# res.append([j,temp[left],temp[right]])
right -= 1
elif j + temp[left]+temp[right] > 0:
right -= 1
else:
left += 1
return dic1.values()
LeetCode 第15题-三数之和的更多相关文章
- 【LeetCode】15、三数之和为0
题目等级:3Sum(Medium) 题目描述: Given an array nums of n integers, are there elements a, b, c in nums such t ...
- 【LeetCode】15. 3Sum 三数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, 三数之和,题解,leetcode, 力扣,P ...
- LeeCode数组第15题三数之和
题目:三数之和 内容: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中 ...
- leetcode 刷题(数组篇)15题 三数之和 (双指针)
很有意思的一道题,值得好好思考,虽然难度只有Mid,但是个人觉得不比Hard简单 题目描述 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b ...
- Leetcode(15)-三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...
- [LeetCode] 259. 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- 【JavaScript】Leetcode每日一题-平方数之和
[JavaScript]Leetcode每日一题-平方数之和 [题目描述] 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c . 示例1: 输入:c = 5 ...
- [LeetCode] 15. 3Sum 三数之和
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- [LeetCode] 3Sum Closest 最近三数之和
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
随机推荐
- Linux 旗标实现
Linux 内核提供了一个遵守上面语义的旗标实现, 尽管术语有些不同. 为使用旗标, 内核 代码必须包含 <asm/semaphore.h>. 相关的类型是 struct semaphor ...
- 微信小程序之在线试题(1)
最近在做一套公司的市场化培训项目,涉及到手机端在线答题的设计,首先摒弃app的模式,那就只剩下微信公众号和小程序,而公众号是可以关联小程序,所以我们只需要做好一套小程序. 因为篇幅问题,下面只讲解在线 ...
- 【30.01%】【hdu 3397】Sequence operation
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submissio ...
- Hamcrest Tutorial
Java Hamcrest Home Hamcrest Tutorial Introduction Hamcrest is a framework for writing matcher object ...
- Linux 内核 动态设备
术语"热插拔"最普遍使用的意义产生于当讨论这样的事实时, 几乎所有的计算机系统现在 能够处理当系统有电时设备的出现或消失. 这非常不同于只是几年前的计算机系统, 那时 程序员知道他 ...
- dll中全局变量在外部进行引用
在Windows中实际导出全局变量,您必须使用类似于export / import语法的语法,例如: #ifdef COMPILING_THE_DLL #define MY_DLL_EXPORT ex ...
- asp.net core 3.0 JObject The collection type 'Newtonsoft.Json.Linq.JObject' is not supported
在asp.net core 3.0 中,如果直接在Controller中返回 Jobject 类型,会抛出如下错误: The collection type 'Newtonsoft.Json.Linq ...
- Python11_文件的读写
1.打开和关闭文件(文件对象的方法open,close) file object = open(file_name [, access_mode][, buffering]) 各个参数的细节如下: f ...
- ERROR StatusLogger Log4j2 could not find a logging implementation.
今天在学习structs2 2.5.5的版本的时候碰到2个问题.第一个网上下的包里面差log4j-core这个包. 虽然程序可以运行,但控制台会报这个错误. ERROR StatusLogger L ...
- 微信小程序酒店日历超强功能
首先利用date拿到年月日 月记得+1 ,因为是从0开始的 先遍历月份,跨年年+1 ,月归至1: 然后遍历天数, lastDat = new Date(val.year,val.month,0).ge ...