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,cd ,使得 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)的更多相关文章

  1. LeetCode 中等题解(3)

    34 在排序数组中查找元素的第一个和最后一个位置 Question 给定一个按照升序排列的整数数组 nums,和一个目标值 target.找出给定目标值在数组中的开始位置和结束位置. 你的算法时间复杂 ...

  2. LeetCode 中等题解(4)

    40 组合总和 II Question 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candidates ...

  3. LeetCode 中等题解(2)

    31 下一个排列 Question 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列. 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列). 必须 ...

  4. LeetCode OJ 题解

    博客搬至blog.csgrandeur.com,cnblogs不再更新. 新的题解会更新在新博客:http://blog.csgrandeur.com/2014/01/15/LeetCode-OJ-S ...

  5. Leetcode 简略题解 - 共567题

    Leetcode 简略题解 - 共567题     写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...

  6. LeetCode 算法题解 js 版 (001 Two Sum)

    LeetCode 算法题解 js 版 (001 Two Sum) 两数之和 https://leetcode.com/problems/two-sum/submissions/ https://lee ...

  7. [leetcode] 位操作题解

    子集 题目[78]:给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 示例: 输入: nums = [1,2,3] 输出: [ [3],   [1],   [2],   [ ...

  8. leetcode & lintcode 题解

    刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...

  9. LeetCode一句话题解

    深度优先搜索 人生经验 1. 需要输出所有解.并由于元素集有重复元素,要求返回的结果需要去重的情况,可考虑使用值对应数量的map,然后分别考虑依次取不同数量该值的可能. LeetCode39 题目:给 ...

随机推荐

  1. nginx优化:配置gzip压缩页面提高访问速度(nginx1.18.0)

    一,为什么nginx要使用gzip 1,压缩的作用: 页面使用gzip压缩之后, 页面大小可以压缩到原来的1/7左右, 传输速度和页面打开时间都可以大幅度提高, 有利于用户访问页面体验的提升 2,Ng ...

  2. 实现LNMP架构

    LNMP简介 WEB资源类型: 静态资源:服务器端和客户端看到的是一样的 动态资源:服务器端放的是程序,客户端看到的是结果,并不是程序本身 和页面的静或者动没有关系 WEB相关语言 HTML JAVA ...

  3. Linux运维学习第五周记

    休惊岁岁年年貌 且对朝朝暮暮人 细雨晴时一百六 画船鼍鼓莫违民 雨生百谷,春雨贵如油 第五周学记 这周主要学习了九三级磁盘.存储相关知识和Linux文件系统以及计算机网络的内容 磁盘和文件系统 磁盘结 ...

  4. CC2530定时器模模式最大值计算

    首先假设 频率: f 分频系数: n 间隔定时: s 周期: T 模模式最大值: N 因为 T = 1 / f 所以 s = ( n / f ) * N  =  n * N / f 由此可得 计算模模 ...

  5. SpringMVC的@InitBinder参数转换

    @Controller @RequestMapping("/index") public class IndexController { /** * 解决前端传递的日期参数验证异常 ...

  6. 冷饭新炒:理解断路器CircuitBreaker的原理与实现

    前提 笔者之前在查找Sentinel相关资料的时候,偶然中找到了Martin Fowler大神的一篇文章<CircuitBreaker>.于是花了点时间仔细阅读,顺便温习一下断路器Circ ...

  7. requests库响应消息体的四种格式

    1.r.text  文本响应内容,返回字符串类型,获取网页html时用: 2.r.content  字节响应内容,返回字节类型,下载图片或者文件时用: 3.r.json json解码响应内容,返回字典 ...

  8. 水题挑战4: luogu P1280 尼克的任务

    题目描述 尼克每天上班之前都连接上英特网,接收他的上司发来的邮件,这些邮件包含了尼克主管的部门当天要完成的全部任务,每个任务由一个开始时刻与一个持续时间构成. 尼克的一个工作日为 \(n\) 分钟,从 ...

  9. [P2114] [NOI2014]起床困难综合症 (位运算)

    题面 传送门:https://www.luogu.org/problemnew/show/P2114 Solution 一道很有意思的位运算题. 要做这一题,我们首先得了解一个很重要的特点 位运算过程 ...

  10. 848.Shifting Letters——weekly contest 87

    848. Shifting Letters 题目链接:https://leetcode.com/problems/shifting-letters/description/ 思路:O(N^2)复杂度过 ...