【Leetcode】两数之和,三数之和,四数之和
两数之和
题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答
1,爆破,O(N^2)
2,要找到任意 x + y = target,同等于 y = target - x,那么 把外层作为 x 遍历,查询 y 在不在列表即可,查询用哈希优化复杂度O(1)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash_dict = {}
for index, x in enumerate(nums):
y = target - x
if y in hash_dict:
return [hash_dict[y], index]
hash_dict[x] = index
三数之和
题目
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解答
1,爆破,时间复杂度太高,O(N^3)。Time: O(N^3), Space: O(1)
def threeSum(self, nums):
# 爆破
pass
2,排序+双指针,外层遍历作为a,内层用双指针寻找b c,使得a+b+c=0。Time: O(N^2), Space: O(1)
具体思路如下:
标签:数组遍历
首先对数组进行排序,排序后固定一个数 nums[i]nums[i],再使用左右指针指向 nums[i]nums[i]后面的两端,数字分别为 nums[L]nums[L] 和 nums[R]nums[R],计算三个数的和 sumsum 判断是否满足为 00,满足则添加进结果集
如果 nums[i]nums[i]大于 00,则三数之和必然无法等于 00,结束循环
如果 nums[i]nums[i] == nums[i-1]nums[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
当 sumsum == 00 时,nums[L]nums[L] == nums[L+1]nums[L+1] 则会导致结果重复,应该跳过,L++L++
当 sumsum == 00 时,nums[R]nums[R] == nums[R-1]nums[R−1] 则会导致结果重复,应该跳过,R--R−−
时间复杂度:O(n^2),n为数组长度
class Solution:
def threeSum(self, nums):
if not nums or len(nums) < 3:
return []
nums.sort() # 先排序
ans = []
lenth = len(nums)
for i in range(lenth): # 外层循环
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]: # 防止相邻i相同出现重复值,不要比较i和i+1,因为当前i和i+1也许会和其他一个数组成一个元祖
continue
L = i + 1
R = lenth - 1
while L < R:
sum = nums[i] + nums[L] + nums[R]
if sum < 0:
L += 1
elif sum > 0:
R -= 1
elif sum == 0:
ans.append([nums[i], nums[L], nums[R]]) # 找到
while L < R and nums[L] == nums[L + 1]: # 防止相邻L相同出现重复值
L += 1
while L < R and nums[R] == nums[R - 1]: # 防止相邻R相同出现重复值
R -= 1
L += 1 # 继续走
R -= 1
return ans
3,遍历外面两层a b,判断c在不在内层,内层用哈希表查找O(1)。Time: O(N^2), Space: O(N)
def threeSum(self, nums):
if len(nums) < 3:
return []
nums.sort()
ans = set()
for i, a in enumerate(nums[:-2]):
if a > 0:
break
if i > 0 and a == nums[i-1]:
continue
hash_dict = {}
for b in nums[i+1:]:
if b not in hash_dict: # 把 c 加入哈希表
hash_dict[-(a+b)] = 1
else:
ans.add((a, -(a+b), b))
return map(list, ans)
【Leetcode】两数之和,三数之和,四数之和的更多相关文章
- 【leetcode 简单】第三题 回文数
判断一个整数是否是回文数.回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数. 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向 ...
- LeetCode:两数之和、三数之和、四数之和
LeetCode:两数之和.三数之和.四数之和 多数之和问题,利用哈希集合减少时间复杂度以及多指针收缩窗口的巧妙解法 No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在 ...
- [LintCode/LeetCode]——两数和、三数和、四数和
LintCode有大部分题目来自LeetCode,但LeetCode比较卡,下面以LintCode为平台,简单介绍我AC的几个题目,并由此引出一些算法基础. 1)两数之和(two-sum) 题目编号: ...
- 【LeetCode】18、四数之和
题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...
- 【算法训练营day7】LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和
[算法训练营day7]LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之和 LeetCode18. 四数之和 LeetCode454. 四数相加I ...
- [LeetCode] 454. 4Sum II 四数之和II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...
- LeetCode:四数之和【18】
LeetCode:四数之和[18] 题目描述 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c ...
- 【LeetCode】 454、四数之和 II
题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...
- 【数据结构】Hash表简介及leetcode两数之和python实现
文章目录 Hash表简介 基本思想 建立步骤 问题 Hash表实现 Hash函数构造 冲突处理方法 leetcode两数之和python实现 题目描述 基于Hash思想的实现 Hash表简介 基本思想 ...
- 【LeetCode】18.四数之和
题目描述 18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...
随机推荐
- iotop实时监控磁盘io
介绍 Linux下的IO统计工具如iostat, nmon等大多数是只能统计到per设备的读写情况, 如果你想知道每个进程是如何使用IO的就比较麻烦. iotop 是一个用来监视磁盘 I/O 使用状况 ...
- idea永久使用本地的maven设置
1.要想是永久的,就选择other settings
- 洛谷 P3750 [六省联考2017]分手是祝愿
传送门 题解 //Achen #include<algorithm> #include<iostream> #include<cstring> #include&l ...
- python 与 selenium 学习笔记
在写自动运行测试用例,并且生成HTML报告的时候,遇到了这个报错: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in positi ...
- 02Redis入门指南笔记(基本数据类型)
一:热身 获得符合规则的健名列表:keys pattern pattern支持glob风格的通配符,具体规则如下表: Redis命令不区分大小写.keys命令需要遍历Redis中的所有健,当键的数量 ...
- 干货来了!2019阿里云合作伙伴峰会SaaS加速器专场回顾合集:嘉宾分享、深度解读
2019年7月26日,在上海举办的阿里云合作伙伴峰会上,阿里云正式发布SaaS生态战略,计划用阿里云的品牌.渠道.资本.方法论.技术加持伙伴,成就亿级营收独角兽. 该生态战略计划招募10家一级SaaS ...
- LUOGU P3435 [POI2006]OKR-Periods of Words
传送门 解题思路 首先求出kmp,那么i-nxt[i]一定是一个周期,对于每一个点一直跳nxt,跳到最小的nxt之后用i-这个nxt即为i这个前缀的答案. 代码 #include<iostrea ...
- nginx、php-fpm启动脚本
Nginx官方启动脚本 //service nginx stop|start|restart|reloadtouch /etc/init.d/nginx chmod nginxvi /etc/init ...
- Hackerrank--String Function Calculation(后缀数组)
题目链接 Jane loves string more than anything. She made a function related to the string some days ago a ...
- 关于JavaScript的一些不得不知道的事儿
1.JavaScript不区分整数和浮点数,统一用Number表示. 2.NaN这个特殊的Number与所有其他值都不相等,包括它自己: NaN===NaN; //false 唯一能判断NaN的方法是 ...