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 之 三 TCP/IP 及 子网划分
TCP/IP TCP/IP 协议集或协议簇 概念: 传输控制协议/IRI特网协议(TCP/IP)组是由美国国防比(DoD)所创建的,主要用来确保数据的完整性及毁灭性战争中维持通信 是有一组不同功能的协 ...
- surfer白化
surfer白化的方法: 方法一: 1.griddata需白化的文件(surfer处理成grd格式,也就是surfer绘图的基本数据格式) 注意:用surfer转换格式时,插值间距(spacing)大 ...
- OC中ARC forbids explicit message send of release错误
在ios编程中,如果成员变量为对象,我们需要对成员变量内存管理,否则,会造成内存泄露.即我们要对成员变量进行手动的内存释放. 很显然,是ARC的问题. 错误原因:在创建工程的时候点选了“Use Aut ...
- 《Windows内核安全与驱动开发》阅读笔记 -- 索引目录
<Windows内核安全与驱动开发>阅读笔记 -- 索引目录 一.内核上机指导 二.内核编程环境及其特殊性 2.1 内核编程的环境 2.2 数据类型 2.3 重要的数据结构 2.4 函数调 ...
- 西瓜哥:公有云也“All-Flash”?
本文转载自 高端存储知识 Gartner在2018年Market Insight: Preparing for the SSD Rise and HDD Demise一文中指出:当闪存介质降到HDD每 ...
- 转:关于JAVA项目中CLASSPATH路径详解
在dos下编译Java程序,就要用到classpath这个概念,尤其是在没有设置环境变量的时候.classpath就是存放.class等编译后文件的路径. javac:如果当前你要编译的Java文件中 ...
- CSS给元素清除浮动影响的方法,--最全四种方法
代码实例: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- Java修炼——文件夹的复制
文件夹的复制用到了俩个流:缓冲流和文件字节流 缓冲流用来加快写入和读取速度. 在这里我简述一下复制文件夹的过程,当然复制文件夹都可以,复制文件更是不在话下 1.首先要明确俩点.要复制的文件夹的位置(源 ...
- [TimLinux] django model关于QuerySet
1. 获取执行过的sql命令 from django.db import connections connections['default'].queries 2. 获取QuerySet将执行的sql ...
- 洛谷 题解 P3385 【【模板】负环】
一.声明 在下面的描述中,未说明的情况下,\(N\) 是顶点数,\(M\)是边数. 二.判负环算法盘点 想到判负环,我们会想到很多的判负环算法.例如: 1. Bellman-Ford 判负环 这个算法 ...