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. MATLAB中cell函数用法

    cell元包是matlab中提供的一种数据类型,功能强大. 关于cell的创建: 1.跟一般创建举证一样,直接使用C = {A B D E}这种形式,不过这里把"[]"改成了}&q ...

  2. JPA配置实体时 insertable = false, updatable = false

    当使用JPA配置实体时,如果有两个属性(一个是一般属性,一个是多对一的属性)映射到数据库的同一列,就会报错. 这时,在多对一的@JoinColumn注解中添加insertable = false, u ...

  3. Forrester:华为云容器是容器混合云最佳选择

    近日,国际权威咨询机构Forrester发布<The Forrester New WaveTM: Public Cloud Enterprise Container Platforms, Q3 ...

  4. SpringBoot整合freemarker模板

    一.目录展示 二.导入依赖 三.application.properties配置文件 四.在src/main/resource/templates文件夹中创建HelloFreeMarker.ftl文件 ...

  5. Python面试180道题

    版权声明:本文为CSDN博主「CSDN学院官方账号」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明. 原文链接:https://blog.csdn.net/csd ...

  6. Java 将Excel转为PDF

    本文将介绍在Java程序中如何将Excel工作簿转为PDF文档的,包括: 将整个工作簿转为PDF 将指定工作表转为PDF   使用工具:Free Spire.XLS for Java (免费版) Ja ...

  7. VSCode 入门

    一 基本布局 二 主题设置 2.1 选择颜色主题 方式一 文件 -> 首选项 -> 颜色主题 -> 上下按键 切换预览 -> enter选择 或者 CTRL + K CTRL ...

  8. openstack网络(二)

    连接物理服务器 单网卡 多网卡 跨主机安装网络服务 使用单个控制节点安装 使用专用网络节点安装 连接物理服务器 每个物理主机所需的网卡数量取决于云平台使用领域,组织的安全性和性能要求以及硬件的可用性. ...

  9. 18.DjangoRestFramework学习一之restful规范、APIview、解析器组件、Postman等

    一 预备知识 预备知识:django的CBV和FBV CBV(class based view):多用,简单回顾一下 FBV(function based view): CBV模式的简单操作:来个登陆 ...

  10. cmake 简介

    CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程).他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的 ...