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数之和的更多相关文章

  1. LeetCode题解001:两数之和

    两数之和 题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个 ...

  2. 【LeetCode题解】2_两数相加

    目录 [LeetCode题解]2_两数相加 描述 方法一:小学数学 思路 Java 代码(非递归写法) Java 代码(递归写法) Python 代码(非递归写法) [LeetCode题解]2_两数相 ...

  3. 【LeetCode】 454、四数之和 II

    题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...

  4. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  5. LeetCode#15 | Three Sum 三数之和

    一.题目 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组. 注意:答案中不可以包含 ...

  6. 【JavaScript】Leetcode每日一题-平方数之和

    [JavaScript]Leetcode每日一题-平方数之和 [题目描述] 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c . 示例1: 输入:c = 5 ...

  7. Leetcode:0002(两数之和)

    LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...

  8. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

  9. leetcode.双指针.633平方数之和-Java

    1. 具体题目 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c. 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 注 ...

随机推荐

  1. jitter()函数的使用

    jitter()函数:对数值向量添加一个小的噪音量. jitter(x,factor=1,amount=NULL) ·x:数值变量,需要加入噪音的数值向量: ·factor:数值型: ·amount: ...

  2. C语言Ⅰ博客作业04

    问题 回答 这个作业属于哪个课程 c语言程序设计ll 这个作业要求在哪里 https://blog.csdn.net/qq_42264638/article/details/102381471 我在这 ...

  3. jsp 实现查询功能

    要求: 实现查询功能 1.数据库代码 create database mvce; use mvce; create table test2( id int not null identity, tna ...

  4. 源码分析 RocketMQ DLedger 多副本之 Leader 选主

    目录 1.DLedger关于选主的核心类图 1.1 DLedgerConfig 1.2 MemberState 1.3 raft协议相关 1.4 DLedgerRpcService 1.5 DLedg ...

  5. 震惊!线上四台机器同一时间全部 OOM,到底发生了什么?

    案发现场 昨天晚上突然短信收到 APM (即 Application Performance Management 的简称),我们内部自己搭建了这样一套系统来对应用的性能.可靠性进行线上的监控和预警的 ...

  6. 【跟唐老师学习云网络】-第8篇 iptables - filter过滤功能

    [摘要] 前面的各种协议已经可以把基本可用的物理网络世界给形成了,在正常情况下,它可以玩的很溜.比如组个局域网办公,或者打个联机魔兽争霸,都没有什么问题. 一.背景介绍 前面的各种协议已经可以把基本可 ...

  7. 转:java 解析excel,带合并单元的excel

    收集了一些对博主有帮助的博文,如下 >>>>>>>>>>>第一部分: 首先,mavn导入jar包 <!-- 解析excel需要导 ...

  8. 【实用工具】使用Java封装可执行exe应用全过程

    目录 编写java代码 打包 创建exe文件 压缩 总结 本文将使用exe4j将java项目封装为可以发送给他人使用的工具为例,来记录将java项目封装为exe文件的全过程 编写java代码 目标:创 ...

  9. JMeter 实用插件配置

    插件下载地址:链接 观察实时TPS,TRT,多用户负载图. 将 jpgc-graphs-dist-2.0.zip 解压缩至jmeter下的lib目录下,重启jmeter Transactions pe ...

  10. git 多仓库源 配置

    在后台配好ssh公匙后 在C:\Users\Administrator\.ssh 下修改config文件  就叫config不带后缀 若没有则新建 配置SSH 密匙 # 配置github.com Ho ...