Leetcode题解 - 双指针求n数之和
1. 两数之和

"""
双指针,题目需要返回下标,所以记录一个数字对应的下标
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
r = [[ind, num] for ind, num in enumerate(nums)]
r = sorted(r, key=lambda x: x[1])
head = 0
tail = len(r) - 1
while head < tail:
s = r[head][1] + r[tail][1]
if s == target:
return [r[head][0], r[tail][0]]
elif s > target:
tail -= 1
# 跳过重复值,去重的规则都一样(下面的也是这样)
while head < tail and r[tail][1] == r[tail+1][1]:
tail -= 1
else:
head += 1
while head < tail and r[head][1] == r[head-1][1]:
head += 1
15. 三数之和

"""
双指针,所以先固定一个数字,用双指针来找到另外两个数字。注意记得剪枝,否则一定会超时的。(被超时操控的恐惧...
"""
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
vis = set()
res = []
for i in range(len(nums)):
if nums[i] in vis:
continue
if nums[i] > 0:
break
vis.add(nums[i])
head = i + 1
tail = len(nums) - 1
while head < tail and head < len(nums) and tail < len(nums):
s = nums[i] + nums[head] + nums[tail]
if not s:
res.append([nums[i], nums[head], nums[tail]])
head += 1
tail -= 1
# 跳过重复元素
while head < tail and nums[head] == nums[head - 1]:
head += 1
while head < tail and nums[tail] == nums[tail + 1]:
tail -= 1
if s > 0:
tail -= 1
while head < tail and nums[tail] == nums[tail + 1]:
tail -= 1
if s < 0:
head += 1
while head < tail and nums[head] == nums[head - 1]:
head += 1
return res
18. 四数之和

"""
固定两个,双指针找另外两个
"""
class Solution:
def fourSum(self, nums, target):
nums.sort()
res = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
head = j + 1
tail = len(nums) - 1
while head < tail:
s = nums[i] + nums[j] + nums[head] + nums[tail]
if s == target:
res.append([nums[i], nums[j], nums[head], nums[tail]])
head += 1
tail -= 1
while head < tail and nums[head] == nums[head - 1]:
head += 1
while head < tail and nums[tail] == nums[tail + 1]:
tail -= 1
elif s > target:
tail -= 1
while head < tail and nums[tail] == nums[tail + 1]:
tail -= 1
else:
head += 1
while head < tail and nums[head] == nums[head - 1]:
head += 1
return list(set([tuple(i) for i in res]))
总结
可以看到,无论是2、3or4,都是固定除了双指针之外的元素,再用双指针去找剩下的元素,代码几乎没有改变,切记要记得剪枝。
Leetcode题解 - 双指针求n数之和的更多相关文章
- LeetCode题解001:两数之和
两数之和 题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个 ...
- 【LeetCode题解】2_两数相加
目录 [LeetCode题解]2_两数相加 描述 方法一:小学数学 思路 Java 代码(非递归写法) Java 代码(递归写法) Python 代码(非递归写法) [LeetCode题解]2_两数相 ...
- 【LeetCode】 454、四数之和 II
题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...
- 【LeetCode】18、四数之和
题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...
- LeetCode#15 | Three Sum 三数之和
一.题目 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组. 注意:答案中不可以包含 ...
- 【JavaScript】Leetcode每日一题-平方数之和
[JavaScript]Leetcode每日一题-平方数之和 [题目描述] 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c . 示例1: 输入:c = 5 ...
- Leetcode:0002(两数之和)
LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...
- Leetcode(1)两数之和
Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
- leetcode.双指针.633平方数之和-Java
1. 具体题目 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c. 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 注 ...
随机推荐
- CCNA 之 十三 广域网概述
广域网概述 为什么需要WAN ? 分区或分支机构的员工需要与总部通信并共享数据: 组织经常需要与其他组织远距离共享信息: 经常出差的员工需要访问公司网络信息: 什么事广域网链路? 用于连接LAN的.跨 ...
- 转载:不是书评 :《我是一只IT小小鸟》
本文转载自刘未鹏博客:http://www.mindhacks.cn. 原文地址如下:http://mindhacks.cn/2009/10/05/im-a-tiny-bird-book-review ...
- python安装matplotlib:python -m pip install matplotlib报错
matplotlib是python中强大的画图模块. 首先确保已经安装python,然后用pip来安装matplotlib模块. 进入到cmd窗口下,建议执行python -m pip install ...
- 洛谷 P2388 阶乘之乘 题解
本蒟蒻又来发题解了QwQ; 看到这个题目,本蒟蒻第一眼就想写打个暴力: 嗯,坏习惯: 但是,动动脑子想一想就知道,普通的的暴力是过不了的: 但是,身为蒟蒻的我,也想不出什么高级的数学方法来优化: 好, ...
- luogu P1509 找啊找啊找GF
题目背景 sqybi现在看中了n个MM,我们不妨把她们编号1到n.请MM吃饭是要花钱的,我们假设请i号MM吃饭要花rmb[i]块大洋.而希望骗MM当自己GF是要费人品的,我们假设请第i号MM吃饭试图让 ...
- openlayers6结合geoserver实现地图空间查询(附源码下载)
前言 之前写过一篇 openlayers4 版本的地图空间查询文章,但是由于是封装一层 js 代码写的,很多初学者看起来比较有点吃力,所以本篇文章重新写一篇地图空间查询文章,直接基于最新版本 open ...
- 记录一些实用的小技巧-CSS篇
1.单行文本截断 .text{ width: 200px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } 2.多行 ...
- WebAPI之postman变量和session/token
postman使用变量: 之前我们请求里面的主机地址都是localhost,表示本机.而在实际测试过程中,服务器地址往往并非是在本机上的,这时候就需要用到变量. postman支持多个测试环境,一个环 ...
- 【IntelliJ Idea】常用快捷键
[IntelliJ Idea]常用快捷键 转载:https://www.cnblogs.com/yangchongxing/p/10654018.html ============= 调试 ===== ...
- where和having区别
壹: where后面不能跟聚合函数(sum.avg.count.max.min) having后面可以跟 贰: where和having都能用: select goods_price,goods_na ...