LeetCode 中等题解(1)
16 最接近的三数之和
Question
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Answer
#
# @lc app=leetcode.cn id=16 lang=python3
#
# [16] 最接近的三数之和
#
# @lc code=start
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
n = len(nums)
if (not nums or n < 3):
return None
nums.sort()
res = float("inf")
for i in range(n):
if (i > 0 and nums[i] == nums[i - 1]):
continue
L = i + 1
R = n - 1
while (L < R):
cur_sum = nums[i] + nums[L] + nums[R]
if (cur_sum == target):
return target
if (abs(cur_sum - target) < abs(res - target)):
res = cur_sum
if (cur_sum - target < 0):
L += 1
else:
R -= 1
return res
# @lc code=end
17 电话号码的字母组合
Question
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
Answer
#
# @lc app=leetcode.cn id=17 lang=python3
#
# [17] 电话号码的字母组合
#
# @lc code=start
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
d_dict={
'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']
}
ans_a = []
ans_b = []
for d in digits:
if ans_a == []:
for s in d_dict[d]:
ans_a.append(s)
else:
for s in d_dict[d]:
for i in range(len(ans_a)):
ans_b.append(ans_a[i] + s)
if ans_b != []:
ans_a = ans_b
ans_b = []
return ans_a
# @lc code=end
18 四数之和
Question
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,**b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
Answer
#
# @lc app=leetcode.cn id=18 lang=python3
#
# [18] 四数之和
#
# @lc code=start
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
if not nums or len(nums) < 4:
return []
nums.sort()
res = []
for a in range(len(nums) - 3):
if a > 0 and nums[a] == nums[a - 1]:
continue
for b in range(a + 1, len(nums) - 2):
if b > a + 1 and nums[b] == nums[b - 1]:
continue
c = b + 1
d = len(nums) - 1
while c < d:
sum = nums[a] + nums[b] + nums[c] + nums[d]
if sum == target:
res.append([nums[a], nums[b], nums[c], nums[d]])
while c < d and nums[c] == nums[c + 1]:
c += 1
while c < d and nums[d] == nums[d - 1]:
d -= 1
c += 1
d -= 1
elif sum < target:
c += 1
else:
d -= 1
return res
# @lc code=end
19 删除链表的倒数第N个节点
Question
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
Answer
#
# @lc app=leetcode.cn id=19 lang=python3
#
# [19] 删除链表的倒数第N个节点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
node_no = 0
node = head
while node is not None:
node = node.next
node_no += 1
node_no -= n + 1
node = head
if node_no == -1:
head = head.next
else:
while(node_no):
node = node.next
node_no -= 1
node.next = node.next.next
return head
# @lc code=end
PS: 两边扫描,第一遍拿到删除点位置,第二遍找到删除点进行删除。
22 括号生成
Question
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Answer
#
# @lc app=leetcode.cn id=22 lang=python3
#
# [22] 括号生成
#
# @lc code=start
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
dp = [[] for _ in range(n + 1)]
dp[0] = [""]
for i in range(1, n + 1):
for p in range(i):
l1 = dp[p]
l2 = dp[i - 1 - p]
for k1 in l1:
for k2 in l2:
dp[i].append("({0}){1}".format(k1, k2))
return dp[n]
# @lc code=end
PS:动态规划的理解方法,可以参考这篇题解。
24 两两交换链表中的节点
Question
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
Answer
#
# @lc app=leetcode.cn id=24 lang=python3
#
# [24] 两两交换链表中的节点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
node_id = 0
head_pre = head
big_node = None
ans = head.next
while (head.next):
head = head.next
node_id += 1
if node_id % 2 == 1:
head_pre.next = head.next
if big_node is not None:
big_node.next = head
head.next = head_pre
head = head.next
big_node = head
head_pre = head
return ans
# @lc code=end
PS:注意只有零个节点或者一个节点的极端情况。
29 两数相除
Question
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2
说明:
- 被除数和除数均为 32 位有符号整数。
- 除数不为 0。
- 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
Answer
#
# @lc app=leetcode.cn id=29 lang=python3
#
# [29] 两数相除
#
# @lc code=start
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
i, a, b = 0, abs(dividend), abs(divisor)
if a == 0 or a < b:
return 0
while b <= a:
b = b << 1
i = i + 1
else:
res = (1 << (i - 1)) + self.divide(a - (b >> 1), abs(divisor))
if (dividend ^ divisor) < 0:
res = -res
return min(res, (1 << 31) - 1)
# @lc code=end
PS:来自评论区算法,实在是太强了。
LeetCode 中等题解(1)的更多相关文章
- LeetCode 中等题解(3)
34 在排序数组中查找元素的第一个和最后一个位置 Question 给定一个按照升序排列的整数数组 nums,和一个目标值 target.找出给定目标值在数组中的开始位置和结束位置. 你的算法时间复杂 ...
- LeetCode 中等题解(4)
40 组合总和 II Question 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candidates ...
- LeetCode 中等题解(2)
31 下一个排列 Question 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列. 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列). 必须 ...
- LeetCode OJ 题解
博客搬至blog.csgrandeur.com,cnblogs不再更新. 新的题解会更新在新博客:http://blog.csgrandeur.com/2014/01/15/LeetCode-OJ-S ...
- Leetcode 简略题解 - 共567题
Leetcode 简略题解 - 共567题 写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...
- LeetCode 算法题解 js 版 (001 Two Sum)
LeetCode 算法题解 js 版 (001 Two Sum) 两数之和 https://leetcode.com/problems/two-sum/submissions/ https://lee ...
- [leetcode] 位操作题解
子集 题目[78]:给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 示例: 输入: nums = [1,2,3] 输出: [ [3], [1], [2], [ ...
- leetcode & lintcode 题解
刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...
- LeetCode一句话题解
深度优先搜索 人生经验 1. 需要输出所有解.并由于元素集有重复元素,要求返回的结果需要去重的情况,可考虑使用值对应数量的map,然后分别考虑依次取不同数量该值的可能. LeetCode39 题目:给 ...
随机推荐
- Flink on Yarn三部曲之一:准备工作
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 电子阅读器.vbs
CreateObject("SAPI.SpVoice").Speak"你要说的话!"
- Spring笔记(4) - Spring的编程式事务和声明式事务详解
一.背景 事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能正常为客户服务,但是也难免遇到操作 ...
- Mybatis原理之数据源和连接池
在Java工程项目中,我们常会用到Mybatis框架对数据库中的数据进行增删查改,其原理就是对 JDBC 做了一层封装,并优化数据源的连接. 我们先来回顾下 JDBC 操作数据库的过程. JDBC 操 ...
- Typora图片一键传——picgo使用兰空图床
Typora picgo使用兰空图床 最近smms图床免费版的速度眼看着越来越慢,特别是到晚上,图片几乎是在原地打转,于是我想替换掉Typora中picgo默认使用的smms图床,网上的教程清一色地只 ...
- ERP仓库管理的操作与设计--开源软件诞生20
赤龙ERP库房管理讲解--第20篇 用日志记录"开源软件"的诞生 [点亮星标]----祈盼着一个鼓励 博主开源地址: 码云:https://gitee.com/redragon/r ...
- ceil中有-0啊
这里主要是有一点: 1 Math.ceil(d1) ceil 方法上有这么一段注释:If the argument value is less than zero but greater ...
- Vue3实战系列:Vue3.0 + Vant3.0 搭建种子项目
最近在用 Vue3 写一个开源的商城项目,开源后让大家也可以用现成的 Vue3 大型商城项目源码来练练手,目前处于开发阶段,过程中用到了 Vant3.0,于是就整理了这篇文章来讲一下如何使用 Vue3 ...
- Spring Boot 学习摘要--关于日志框架
date: 2020-01-05 16:20:00 updated: 2020-01-08 15:50:00 Spring Boot 学习摘要--关于日志框架 学习教程来自:B站 尚硅谷 1. 关于日 ...
- python装饰器是什么?
装饰器是python中的高阶语法,装饰器是通过类或者函数来实现的,通常使用@符号来表示一个装饰器,作用是用来扩展某个函数或者类的功能