Leecode 0570. 至少有5名直接下属的经理
570. 至少有5名直接下属的经理表: Employee 123456789101112+-------------+---------+| Column Name | Type |+-------------+---------+| id | int || name | varchar || department | varchar || managerId | int |+-------------+---------+id 是此表的主键(具有唯一值的列)。该表的每一行表示雇员的名字、他们的部门和他们的经理的id。如果managerId为空,则该员工没有经理。没有员工会成为自己的管理者。 编写一个解决方案,找出至少有五个直接下属的经理。 以 任意顺序 返回结果表。 查询结果格式如下所示。 示例 1: 123456789101112131415161718输入: Employee 表:+-----+-------+------------+-----------+| id | name | department...
Leecode 0626. 换座位
626. 换座位表: Seat 123456789+-------------+---------+| Column Name | Type |+-------------+---------+| id | int || student | varchar |+-------------+---------+id 是该表的主键(唯一值)列。该表的每一行都表示学生的姓名和 ID。ID 序列始终从 1 开始并连续增加。 编写解决方案来交换每两个连续的学生的座位号。如果学生的数量是奇数,则最后一个学生的id不交换。 按 id 升序 返回结果表。 查询结果格式如下所示。 示例 1: 1234567891011121314151617181920212223输入: Seat 表:+----+---------+| id | student |+----+---------+| 1 | Abbot || 2 | Doris || 3 | Emerson || 4 | Green || 5 | Jeames ...
Leecode 0180. 连续出现的数字
180. 连续出现的数字表:Logs 12345678+-------------+---------+| Column Name | Type |+-------------+---------+| id | int || num | varchar |+-------------+---------+在 SQL 中,id 是该表的主键。id 是一个自增列。 找出所有至少连续出现三次的数字。 返回的结果表中的数据可以按 任意顺序 排列。 结果格式如下面的例子所示: 示例 1: 123456789101112131415161718192021输入:Logs 表:+----+-----+| id | num |+----+-----+| 1 | 1 || 2 | 1 || 3 | 1 || 4 | 2 || 5 | 1 || 6 | 2 || 7 | 2 |+----+-----+输出:Result 表:+-----------------+| ConsecutiveNums...
Leecode 0461.hamming-distance
461. 汉明距离两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。 给你两个整数 x 和 y,计算并返回它们之间的汉明距离。 示例 1: 1234567输入:x = 1, y = 4输出:2解释:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑上面的箭头指出了对应二进制位不同的位置。 示例 2: 12输入:x = 3, y = 1输出:1 题目大意 汉明距离是指两个整数的二进制表示中,对应位置二进制位不同的数目。给定两个整数 x 和 y,计算并返回它们之间的汉明距离。 例如: 输入 x=1, y=4,二进制分别为 0001 和 0100,对应位不同的位置有 2 处,输出 2; 输入 x=3, y=1,二进制分别为 0011 和 0001,对应位不同的位置有 1 处,输出 1。 解题思路核心思路是利用异或运算 + 统计 1 的个数,步骤如下: 异或运算(XOR):异或的特性是 “相同为 0,不同为 1”。对 x 和 y 做异或操作,得到的结果 xor_result 中,每一位的 1 都对应 x 和 y...
Leecode 2356. 每位教师所教授的科目种类的数量
2356. 每位教师所教授的科目种类的数量表: Teacher 123456789+-------------+------+| Column Name | Type |+-------------+------+| teacher_id | int || subject_id | int || dept_id | int |+-------------+------+在 SQL 中,(subject_id, dept_id) 是该表的主键。该表中的每一行都表示带有 teacher_id 的教师在系 dept_id 中教授科目 subject_id。 查询每位老师在大学里教授的科目种类的数量。 以 任意顺序 返回结果表。 查询结果格式示例如下。 示例 1: 1234567891011121314151617181920212223242526272829输入: Teacher 表:+------------+------------+---------+| teacher_id | subject_id | dept_id...
Leecode 1193. 每月交易 I
1193. 每月交易 I表:Transactions 123456789101112+---------------+---------+| Column Name | Type |+---------------+---------+| id | int || country | varchar || state | enum || amount | int || trans_date | date |+---------------+---------+id 是这个表的主键。该表包含有关传入事务的信息。state 列类型为 ["approved", "declined"] 之一。 编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。 以 任意顺序 返回结果表。 查询结果格式如下所示。 示例...
Leecode 1934. 确认率
1934. 确认率表: Signups 12345678+----------------+----------+| Column Name | Type |+----------------+----------+| user_id | int || time_stamp | datetime |+----------------+----------+User_id是该表的主键。每一行都包含ID为user_id的用户的注册时间信息。 表: Confirmations 1234567891011+----------------+----------+| Column Name | Type |+----------------+----------+| user_id | int || time_stamp | datetime || action | ENUM |+----------------+----------+(user_id,...
Leecode 0445. Add Two Numbers II
445. Add Two Numbers IIYou are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. 1234567891011121314151617181920212223242526272829303132333435363738394041424344/** * Definition for singly-linked list. * struct ListNode { * int...
Leecode 0059. Spiral Matrix II
59. Spiral Matrix IIGiven a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example 1: 12Input: n = 3Output: [[1,2,3],[8,9,4],[7,6,5]] Example 2: 12Input: n = 1Output: [[1]] Constraints: 1 <= n <= 20 题目大意给定一个正整数 n,生成一个 n×n 的矩阵,其中元素从 1 到 n² 按螺旋顺序填充。 解题思路 创建一个 n×n 的空矩阵 定义四个边界:上、下、左、右 按顺时针方向(右→下→左→上)填充数字 每填充完一行或一列就调整相应的边界 重复步骤 3-4 直到所有数字都被填充 123456789101112131415161718192021222324252627282930313233343536373839class Solution...
Leecode 0048. Rotate Image
48. Rotate ImageYou are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: 12Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]Output: [[7,4,1],[8,5,2],[9,6,3]] Example 2: 12Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]Output:...
Leecode 0054. 螺旋矩阵
54. 螺旋矩阵给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 示例 1: 12输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5] 示例 2: 12输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]输出:[1,2,3,4,8,12,11,10,9,5,6,7] 提示: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 题目大意给定一个 m 行 n...
Leecode 1757. 可回收且低脂的产品
1757. 可回收且低脂的产品表:Products 12345678910+-------------+---------+| Column Name | Type |+-------------+---------+| product_id | int || low_fats | enum || recyclable | enum |+-------------+---------+product_id 是该表的主键(具有唯一值的列)。low_fats 是枚举类型,取值为以下两种 ('Y', 'N'),其中 'Y' 表示该产品是低脂产品,'N' 表示不是低脂产品。recyclable 是枚举类型,取值为以下两种 ('Y', 'N'),其中 'Y' 表示该产品可回收,而 'N' 表示不可回收。 编写解决方案找出既是低脂又是可回收的产品编号。 返回结果 无顺序要求...
Leecode 0503. 下一个更大元素 II
503. 下一个更大元素 II给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。 数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。 示例 1: 12345输入: nums = [1,2,1]输出: [2,-1,2]解释: 第一个 1 的下一个更大的数是 2;数字 2 找不到下一个更大的数; 第二个 1 的下一个最大的数需要循环搜索,结果也是 2。 示例 2: 12输入: nums = [1,2,3,4,3]输出: [2,3,4,-1,4] 解题思路核心思路是单调栈 + 数组翻倍模拟循环,通过将数组复制一份拼接在末尾(模拟循环),利用单调栈高效找到每个元素的下一个更大元素: 模拟循环数组: 将原数组 nums 复制一份并拼接在末尾(如 [1,2,1] 变为...
Leecode 0496. 下一个更大元素 I
496. 下一个更大元素 Inums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。 给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。 对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。 返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。 示例 1: 123456输入:nums1 = [4,1,2], nums2 = [1,3,4,2].输出:[-1,3,-1]解释:nums1 中每个值的下一个更大元素如下所述:- 4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。- 1 ,用加粗斜体标识,nums2 =...
Leecode 0084. 柱状图中最大的矩形
84. 柱状图中最大的矩形给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 求在该柱状图中,能够勾勒出来的矩形的最大面积。 示例 1: 123输入:heights = [2,1,5,6,2,3]输出:10解释:最大的矩形为图中红色区域,面积为 10 示例 2: 12输入: heights = [2,4]输出: 4 解题思路该解法是对单调栈思路的优化实现,通过在数组末尾添加哨兵元素和栈初始化技巧,将左右边界的计算合并到一次遍历中,代码更简洁且效率更高。 核心优化思路 哨兵元素(Sentinel): 在原数组末尾添加 -1(高度为负数的哨兵),确保遍历结束时栈中所有元素都会被弹出计算(相当于 “大火收汁”); 栈初始时推入 -1(索引哨兵),解决栈空时的边界判断问题,同时自然对应 “左侧无更矮柱子” 的情况(left[i] = -1)。 一次遍历计算左右边界: 遍历每个元素作为右侧边界(right),当当前高度小于栈顶高度时,栈顶元素的左右边界均已确定: 右边界:当前索引...
Leecode 0402. 移掉 K 位数字
402. 移掉 K 位数字给你一个以字符串表示的非负整数 num 和一个整数 k ,移除这个数中的 k 位数字,使得剩下的数字最小。请你以字符串形式返回这个最小的数字。 示例 1 : 123输入:num = "1432219", k = 3输出:"1219"解释:移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219 。 示例 2 : 123输入:num = "10200", k = 1输出:"200"解释:移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。 示例 3 : 123输入:num = "10", k = 2输出:"0"解释:从原数字移除所有的数字,剩余为空就是 0 。 解题思路核心思路是单调栈 + 贪心算法,通过维护一个递增的栈来确保剩余数字最小,同时控制移除的数字数量不超过 k: 单调栈逻辑: 遍历字符串中的每个数字,对于当前数字c: 若栈不为空,且栈顶数字大于 c,且仍有可移除的次数(k >...
Leecode 0042. 接雨水
42. 接雨水给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 示例 1: 123输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]输出:6解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 示例 2: 12输入:height = [4,2,0,3,2,5]输出:9 解题思路核心思路是双指针边界,通过每个柱子能接住的雨水量取决于其左右两侧的最高柱子中较矮的那个(短板效应): 边界定义: 对于位置 i,左侧最高柱子高度为 left_max[i]; 右侧最高柱子高度为 right_max[i]; 位置 i 能接住的雨水量为 min(left_max[i], right_max[i]) - height[i](若结果为正,否则为 0)。 优化实现: 采用双指针法,无需额外存储 left_max 和 right_max 数组,将空间复杂度降至 O (1); 用 left 和 right...
Leecode 0316. 去除重复字母
316. 去除重复字母给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 示例 1: 12输入:s = "bcabc"输出:"abc" 示例 2: 12输入:s = "cbacdcbc"输出:"acdb" 核心思路是单调栈 + 贪心算法,通过维护一个单调递增的栈来确保字典序最小,同时利用计数数组判断字符是否还有剩余,确保每个字符只保留一次: 预处理: 统计字符串中每个字符的出现次数(count 数组); 记录字符是否已在栈中(in_stack 数组),避免重复添加。 单调栈逻辑: 遍历字符串中的每个字符C: 减少 count[c](当前字符已被考虑); 若 c 已在栈中,直接跳过; 若 c 不在栈中,且栈不为空,且栈顶字符大于 c,且栈顶字符在后续还有出现(count[栈顶字符] > 0),则弹出栈顶字符(确保字典序更小); 将 c...
Leecode 0409. 最长回文串
409. 最长回文串给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的 回文串 的长度。 在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。 示例 1: 1234输入:s = "abccccdd"输出:7解释:我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。 示例 2: 123输入:s = "a"输出:1解释:可以构造的最长回文串是"a",它的长度是 1。 解题思路核心思路是统计字符频率,利用回文串的特性计算最大长度: 回文串特性: 回文串对称位置的字符相同; 偶数长度的回文串:所有字符出现次数均为偶数; 奇数长度的回文串:仅有一个字符出现奇数次(位于中心),其余均为偶数次。 频率统计: 统计字符串中每个字符的出现次数; 累计所有字符的最大偶数次(例如,出现 5 次的字符可贡献 4 次); 若存在出现奇数次的字符,可在结果中加 1(作为中心字符)。 计算逻辑: 初始化结果...
Leecode 0045. 跳跃游戏 II
45. 跳跃游戏 II给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说,如果你在索引 i 处,你可以跳转到任意 (i + j) 处: 0 <= j <= nums[i] 且 i + j < n 返回到达 n - 1 的最小跳跃次数。测试用例保证可以到达 n - 1。 示例 1: 1234输入: nums = [2,3,1,1,4]输出: 2解释: 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 示例 2: 12输入: nums = [2,3,0,1,4]输出: 2 解题思路核心思路是贪心算法,通过跟踪 “当前跳跃的最远边界” 和 “下一次跳跃的最远可达位置”,在每一步跳跃时选择最优范围,实现最少跳跃次数: 贪心策略: 用 end 表示当前跳跃能到达的最远边界(初始为 0); 用 max_reach 表示从当前位置到 end 之间的所有位置能跳到的最远位置; 用...
Leecode 0055. Jump Game
55. Jump GameYou are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. Example 1: 123Input: nums = [2,3,1,1,4]Output: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: 123Input: nums = [3,2,1,0,4]Output: falseExplanation: You will always arrive at index 3 no matter...
Leecode 0053. Maximum Subarray
53. Maximum SubarrayGiven an integer array nums, find the subarray with the largest sum, and return its sum. Example 1: 123Input: nums = [-2,1,-3,4,-1,2,1,-5,4]Output: 6Explanation: The subarray [4,-1,2,1] has the largest sum 6. Example 2: 123Input: nums = [1]Output: 1Explanation: The subarray [1] has the largest sum 1. Example 3: 123Input: nums = [5,4,-1,7,8]Output: 23Explanation: The subarray [5,4,-1,7,8] has the largest sum 23. 题目大意给定一个整数数组...
Leecode 0455. Assign Cookies
455. Assign CookiesAssume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example...
Leecode 0090. Subsets II
90. Subsets IIGiven an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: 12Input: nums = [1,2,2]Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] Example 2: 12Input: nums = [0]Output: [[],[0]] 题目大意给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(即幂集)。幂集需包含所有可能的子集(包括空集和数组本身),且不能有重复子集,结果顺序可任意。 例如: 输入 nums = [1,2,2],输出 [[],[1],[1,2],[1,2,2],[2],[2,2]](共 6 个子集,无重复); 输入 nums...
Leecode 0046. Permutations
46. PermutationsGiven an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: 12Input: nums = [1,2,3]Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: 12Input: nums = [0,1]Output: [[0,1],[1,0]] Example 3: 12Input: nums = [1]Output: [[1]] 题目大意给定一个无重复元素的整数数组 nums,返回该数组所有可能的全排列。全排列是指包含数组所有元素的有序序列,且每个元素仅出现一次,结果顺序可任意。 例如: 输入 nums = [1,2,3],输出 [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]](共 3! = 6...
Leecode 0491. Non-decreasing Subsequences
491. Non-decreasing SubsequencesGiven an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order. Example 1: 12Input: nums = [4,6,7,7]Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: 12Input: nums = [4,4,3,2,1]Output: [[4,4]] 题目大意给定一个整数数组 nums,返回所有不同的、长度至少为 2 的非递减子序列。子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。 例如: 输入 nums = [4,6,7,7],输出包含...
Leecode 0078. Subsets
78. SubsetsGiven an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: 12Input: nums = [1,2,3]Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: 12Input: nums = [0]Output: [[],[0]] 题目大意给定一个无重复元素的整数数组 nums,返回该数组所有可能的子集(即幂集)。幂集需包含所有可能的子集(包括空集和数组本身),且不能有重复子集,结果顺序可任意。 例如: 输入 nums = [1,2,3],输出 [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]](共 2³=8...
Leecode 0093. Restore IP Addresses
93. Restore IP AddressesA valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots...
Leecode 0131. Palindrome Partitioning
131. Palindrome PartitioningGiven a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example 1: 12Input: s = "aab"Output: [["a","a","b"],["aa","b"]] Example 2: 12Input: s = "a"Output: [["a"]] 题目大意给定一个字符串 s,将其分割成若干个子串,使得每个子串都是回文串。返回所有可能的分割方案。 例如: 输入 s = "aab",输出...
Leecode 0040. Combination Sum II
40. Combination Sum IIGiven a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: 12345678Input: candidates = [10,1,2,7,6,1,5], target = 8Output: [[1,1,6],[1,2,5],[1,7],[2,6]] Example 2: 123456Input: candidates = [2,5,2,1,2], target =...
Leecode 0039. Combination Sum
39. Combination SumGiven an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to...
Leecode 0216. Combination Sum III
216. Combination Sum IIIFind all valid combinations of k numbers that sum up to n such that the following conditions are true: Only numbers 1 through 9 are used. Each number is used at most once. Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. Example 1: 12345Input: k = 3, n = 7Output: [[1,2,4]]Explanation:1 + 2 + 4 = 7There are no other valid combinations. Example 2: 1234567Input: k...
Leecode 0077. Combinations
77. CombinationsGiven two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order. Example 1: 1234Input: n = 4, k = 2Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]Explanation: There are 4 choose 2 = 6 total combinations.Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. Example 2: 123Input: n = 1, k = 1Output: [[1]]Explanation: There is 1 choose 1 = 1 total...
Leecode 0108. Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search TreeGiven an integer array nums where the elements are sorted in ascending order, convert it to a *height-balanced* binary search tree. Example 1: 123Input: nums = [-10,-3,0,5,9]Output: [0,-3,9,-10,null,5]Explanation: [0,-10,5,null,-3,null,9] is also accepted: Example 2: 123Input: nums = [1,3]Output: [3,1]Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. 题目大意给定一个升序排列的整数数组 nums,将其转换为一棵高度平衡的二叉搜索树(BST)。高度平衡的定义是:二叉树的左右两个子树的高度差的绝对值不超过...
Leecode 0106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder TraversalGiven two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. Example 1: 12Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]Output: [3,9,20,null,null,15,7] Example 2: 12Input: inorder = [-1], postorder = [-1]Output: [-1] 题目大意给定一棵二叉树的中序遍历数组 inorder 和后序遍历数组...
Leecode 0103. Binary Tree Zigzag Level Order Traversal
103. Binary Tree Zigzag Level Order Traversal Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). Example 1: 12Input: root = [3,9,20,null,null,15,7]Output: [[3],[20,9],[15,7]] Example 2: 12Input: root = [1]Output: [[1]] Example 3: 12Input: root = []Output: [] 题目大意给定一棵二叉树的根节点,返回其节点值的锯齿形层序遍历。即:第一层从左到右,第二层从右到左,第三层再从左到右,以此类推,交替进行。 例如: 输入 root =...
Leecode 0099. Recover Binary Search Tree
99. Recover Binary Search TreeYou are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Example 1: 123Input: root = [1,3,null,null,2]Output: [3,1,null,null,2]Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. Example 2: 123Input: root = [3,1,4,null,null,2]Output: [2,1,4,null,null,3]Explanation: 2 cannot be in the right...
Leecode 0098. Validate Binary Search Tree
98. Validate Binary Search TreeGiven the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys strictly less than the node's key. The right subtree of a node contains only nodes with keys strictly greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 12Input: root = [2,1,3]Output: true Example 2: 123Input: root =...
Leecode 0096. Unique Binary Search Trees
96. Unique Binary Search TreesGiven an integer n, return *the number of structurally unique **BST'*s (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: 12Input: n = 3Output: 5 Example 2: 12Input: n = 1Output: 1 题目大意给定一个整数 n,计算由 1 到 n 为节点所组成的结构独特的二叉搜索树(BST)的数量。 例如: 输入 n = 3,存在 5 种结构独特的 BST,返回 5; 输入 n = 1,只有 1 种 BST,返回 1。 解题思路计算独特 BST 的数量可以通过动态规划(DP) 实现,核心思路基于以下观察: 若选择 i 作为根节点,则左子树由 1~i-1 构成,右子树由 i+1~n 构成; 左子树的独特结构数量为 dp[i-1],右子树的独特结构数量为...
Leecode 0095. Unique Binary Search Trees II
95. Unique Binary Search Trees IIGiven an integer n, return *all the structurally unique **BST'*s (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. Example 1: 12Input: n = 3Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] Example 2: 12Input: n = 1Output: [[1]] 题目大意给定一个整数 n,生成所有由 1 到 n 为节点所组成的结构独特的二叉搜索树(BST)。返回这些二叉搜索树的根节点列表。 二叉搜索树的特性是:对于任意节点,其左子树中的所有节点值都小于该节点值,右子树中的所有节点值都大于该节点值。 例如: 输入 n =...
Leecode 0112. Path Sum
112. Path SumGiven the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. Example 1: 123Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output: trueExplanation: The root-to-leaf path with the target sum is shown. Example 2: 123456Input: root = [1,2,3], targetSum = 5Output: falseExplanation: There are two root-to-leaf...
Leecode 0513. Find Bottom Left Tree Value
513. Find Bottom Left Tree ValueGiven the root of a binary tree, return the leftmost value in the last row of the tree. Example 1: 12Input: root = [2,1,3]Output: 1 Example 2: 12Input: root = [1,2,3,4,null,5,6,null,null,7]Output: 7 题目大意给定一棵二叉树的根节点 root,返回树的最后一行中最左边的节点值。即需要找到二叉树最深一层的最左侧节点的值。 例如: 输入二叉树 [2,1,3],最深层是第 2 层,最左侧节点值为 1,返回 1; 输入二叉树 [1,2,3,4,null,5,6,null,null,7],最深层是第 4 层,最左侧节点值为 7,返回 7。 解题思路找到树左下角的值,关键是确定最深层和该层的最左侧节点。主要有两种实现方法: 1....
Leecode 0404. Sum of Left Leaves
404. Sum of Left LeavesGiven the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. Example 1: 123Input: root = [3,9,20,null,null,15,7]Output: 24Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. Example 2: 12Input: root = [1]Output: 0 题目大意给定一棵二叉树的根节点 root,返回所有左叶子的节点值之和。左叶子的定义是:既是叶子节点(没有子节点),又是其父节点的左子节点。 例如: 输入二叉树 [3,9,20,null,null,15,7],左叶子为...
Leecode 0572. Subtree of Another Tree
572. Subtree of Another TreeGiven the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself. Example 1: 12Input: root = [3,4,5,1,2], subRoot = [4,1,2]Output: true Example 2: 12Input: root =...
Leecode 0100. Same Tree
100. Same TreeGiven the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: 12Input: p = [1,2,3], q = [1,2,3]Output: true Example 2: 12Input: p = [1,2], q = [1,null,2]Output: false Example 3: 12Input: p = [1,2,1], q = [1,1,2]Output: false 题目大意给定两棵二叉树的根节点 p 和 q,判断这两棵树是否相同。两棵树相同的定义是:结构完全相同,且对应节点的值也相同。 例如: 输入两棵结构和节点值均相同的树...
Leecode 0257. Binary Tree Paths
257. Binary Tree PathsGiven the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. Example 1: 12Input: root = [1,2,3,null,5]Output: ["1->2->5","1->3"] Example 2: 12Input: root = [1]Output: ["1"] 题目大意给定一棵二叉树的根节点 root,返回所有从根节点到叶子节点的路径。叶子节点是指没有子节点的节点,路径以字符串形式表示,节点值之间用 "->" 连接。 例如: 输入二叉树 [1,2,3,null,5],根到叶子的路径为 1->2->5 和 1->3,返回...
Leecode 0110. Balanced Binary Tree
110. Balanced Binary TreeGiven a binary tree, determine if it is height-balanced. Example 1: 12Input: root = [3,9,20,null,null,15,7]Output: true Example 2: 12Input: root = [1,2,2,3,3,null,null,4,4]Output: false Example 3: 12Input: root = []Output: true 题目大意给定一棵二叉树,判断它是否是高度平衡的。高度平衡平衡二叉树 ** 的定义是:二叉树的每个节点的左右两个子树的高度差的绝对值不超过 1。 例如: 输入二叉树 [3,9,20,null,null,15,7],每个节点的左右子树高度差均不超过 1,返回 true; 输入二叉树 [1,2,2,3,3,null,null,4,4],根节点的左子树高度为 3,右子树高度为 1,差为 2,返回...
Leecode 0222. Count Complete Tree Nodes
222. Count Complete Tree NodesGiven the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. Example 1: 12Input: root = [1,2,3,4,5,6]Output: 6 Example 2: 12Input: root...
Leecode 0101. Symmetric Tree
101. Symmetric TreeGiven the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: 12Input: root = [1,2,2,3,4,4,3]Output: true Example 2: 12Input: root = [1,2,2,null,3,null,3]Output: false 题目大意给定一棵二叉树的根节点 root,判断该二叉树是否是对称的(即围绕中心轴镜像对称)。 例如: 输入二叉树 [1,2,2,3,4,4,3],其左子树与右子树成镜像,故返回 true; 输入二叉树 [1,2,2,null,3,null,3],左子树与右子树不镜像,故返回 false。 解题思路判断二叉树是否对称的核心是比较左子树与右子树是否成镜像,即: 左子树的左节点需与右子树的右节点值相等; 左子树的右节点需与右子树的左节点值相等。 1....
Leecode 0226. Invert Binary Tree
226. Invert Binary TreeGiven the root of a binary tree, invert the tree, and return its root. Example 1: 12Input: root = [4,2,7,1,3,6,9]Output: [4,7,2,9,6,3,1] Example 2: 12Input: root = [2,1,3]Output: [2,3,1] Example 3: 12Input: root = []Output: [] 题目大意给定一棵二叉树的根节点 root,翻转这棵二叉树(即交换每个节点的左子树和右子树),并返回翻转后的根节点。 例如: 输入二叉树 [4,2,7,1,3,6,9],翻转后每个节点的左右子树互换,输出为 [4,7,2,9,6,3,1]。 解题思路翻转二叉树的核心是交换每个节点的左子节点和右子节点,可以通过递归或迭代两种方式实现: 1....
Leecode 0104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary TreeGiven the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: 12Input: root = [3,9,20,null,null,15,7]Output: 3 Example 2: 12Input: root = [1,null,2]Output: 2 题目大意给定一棵二叉树的根节点 root,返回该二叉树的最大深度。二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数量。 例如: 输入二叉树 [3,9,20,null,null,15,7],其最大深度为 3(路径:3 → 20 → 15 或 3 → 20 → 7,均包含 3...
Leecode 0116. Populating Next Right Pointers in Each Node
116. Populating Next Right Pointers in Each NodeYou are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: 123456struct Node { int val; Node *left; Node *right; Node *next;} Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Example 1: 123Input: root =...
Leecode 0515. Find Largest Value in Each Tree Row
515. Find Largest Value in Each Tree RowGiven the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed). Example 1: 12Input: root = [1,3,2,5,3,null,9]Output: [1,3,9] Example 2: 12Input: root = [1,2,3]Output: [1,3] 题目大意给定一棵二叉树的根节点 root,返回一个数组,其中每个元素是二叉树对应行(从 0 开始索引)中的最大值。 例如: 输入二叉树 [1,3,2,5,3,null,9],第 0 行最大值为 1,第 1 行最大值为 3,第 2 行最大值为 9,因此返回...
Leecode 0429. N-ary Tree Level Order Traversal
429. N-ary Tree Level Order TraversalGiven an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example 1: 12Input: root = [1,null,3,2,4,null,5,6]Output: [[1],[3,2,4],[5,6]] Example 2: 12Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]Output:...
Leecode 0637. Average of Levels in Binary Tree
637. Average of Levels in Binary TreeGiven the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. Example 1: 1234Input: root = [3,9,20,null,null,15,7]Output: [3.00000,14.50000,11.00000]Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.Hence return [3, 14.5, 11]. Example 2: 12Input: root = [3,9,20,15,7]Output:...
Leecode 0199. Binary Tree Right Side View
199. Binary Tree Right Side ViewGiven the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Explanation: Example 2: Input: root = [1,2,3,4,null,null,null,5] Output: [1,3,4,5] Explanation: Example 3: Input: root = [1,null,3] Output: [1,3] Example 4: Input: root = [] Output: [] 题目大意给定一棵二叉树的根节点...
Leecode 0107. Binary Tree Level Order Traversal II
107. Binary Tree Level Order Traversal IIGiven the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). Example 1: 12Input: root = [3,9,20,null,null,15,7]Output: [[15,7],[9,20],[3]] Example 2: 12Input: root = [1]Output: [[1]] Example 3: 12Input: root = []Output: [] 题目大意给定一棵二叉树的根节点 root,返回其节点值的自底向上的层序遍历结果。即按「从叶子节点所在层到根节点所在层」的顺序逐层返回,每层内部仍保持「从左到右」的顺序。 例如: 输入二叉树...
Leecode 0145. Binary Tree Postorder Traversal
145. Binary Tree Postorder TraversalGiven the root of a binary tree, return the postorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,6,7,5,2,9,8,3,1] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] 题目大意给定一棵二叉树的根节点 root,返回其节点值的后序遍历结果。后序遍历的顺序是「左子树 → 右子树 → 根节点」,遵循 "左 - 右 - 根"...
Leecode 0144. Binary Tree Preorder Traversal
144. Binary Tree Preorder TraversalGiven the root of a binary tree, return the preorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [1,2,4,5,6,7,3,8,9] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] 题目大意给定一棵二叉树的根节点 root,返回其节点值的前序遍历结果。前序遍历的顺序是「根节点 → 左子树 → 右子树」,遵循 "根 - 左 - 右"...
Leecode 0094. Binary Tree Inorder Traversal
94. Binary Tree Inorder TraversalGiven the root of a binary tree, return the inorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,3,2] Explanation: Example 2: Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] Output: [4,2,6,5,7,1,3,9,8] Explanation: Example 3: Input: root = [] Output: [] Example 4: Input: root = [1] Output: [1] 题目大意 给定一棵二叉树的根节点 root,返回其节点值的中序遍历结果。中序遍历的顺序是「左子树 → 根节点 → 右子树」,遵循 “左 - 根 - 右”...
Leecode 0239. Sliding Window Maximum
239. Sliding Window MaximumYou are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example 1: 1234567891011Input: nums = [1,3,-1,-3,5,3,6,7], k = 3Output: [3,3,5,5,6,7]Explanation: Window position Max--------------- -----[1 3 -1] -3 5 3 6...
Leecode 0102. Binary Tree Level Order Traversal
102. Binary Tree Level Order TraversalGiven the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). Example 1: 12Input: root = [3,9,20,null,null,15,7]Output: [[3],[9,20],[15,7]] Example 2: 12Input: root = [1]Output: [[1]] Example 3: 12Input: root = []Output: [] 题目大意给定一棵二叉树的根节点 root,返回其节点值的层序遍历结果(即从左到右、逐层遍历)。结果需以二维数组形式呈现,每一层的节点值构成一个子数组(例如,第一层 [根节点],第二层 [左子节点,...
Leecode 0020. Valid Parentheses
20. Valid ParenthesesGiven a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. 题目大意给定一个只包含 '('、')'、'{'、'}'、'[' 和...
Leecode 1047. Remove All Adjacent Duplicates In String
1047. Remove All Adjacent Duplicates In StringYou are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique. Example 1: 1234Input: s = "abbaca"Output: "ca"Explanation: For example, in...
Leecode 0155. Min Stack
155. Min StackDesign a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function. 题目大意设计一个支持...
Leecode 0227. Basic Calculator II
227. Basic Calculator IIGiven a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). 题目大意给定一个字符串 s 表示一个算术表达式,要求计算该表达式的值并返回。表达式仅包含非负整数、+、-、*、/...
Leecode 0150. Evaluate Reverse Polish Notation
150. Evaluate Reverse Polish NotationYou are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression. Note that: The valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward zero. There will not be any division by zero. The input...
Leecode 0071. Simplify Path
71. Simplify PathYou are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path. The rules of a Unix-style file system are as follows: A single period '.' represents the current directory. A double period '..' represents the previous/parent directory. Multiple consecutive slashes such as '//' and '///' are treated as a single slash...
Leecode 0225. Implement Stack using Queues
225. Implement Stack using QueuesImplement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: void push(int x): Pushes element x to the top of the stack. int pop(): Removes the element on the top of the stack and returns it. int top(): Returns the element on the top of the stack. boolean empty(): Returns true if the stack is empty, false...
Leecode 0232. Implement Queue using Stacks
232. Implement Queue using StacksImplement a first in first out (FIFO) queue using only two Stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false...
Leecode 1048. Longest String Chain
1048. Longest String ChainYou are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".A word chain is a sequence of words [word1, word2, ..., wordk] with k...
Leecode 1023. Camelcase Matching
1023. Camelcase MatchingGiven an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters into the pattern so that it equals the query. You may insert a character at any position in pattern or you may choose not to insert any characters at all. Example 1: 12345Input: queries =...
Leecode 0825. Friends Of Appropriate Ages
825. Friends Of Appropriate AgesThere are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 * age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise, x will send a friend request to y. Note that if x sends a request to y, y will not necessarily send a request to x. Also, a...
Leecode 0826. Most Profit Assigning Work
826. Most Profit Assigning WorkYou have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then...
Leecode 0611. Valid Triangle Number
611. Valid Triangle NumberGiven an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: 123456Input: nums = [2,2,3,4]Output: 3Explanation: Valid combinations are: 2,3,4 (using the first 2)2,3,4 (using the second 2)2,2,3 Example 2: 12Input: nums = [4,2,3,4]Output: 4 题目大意给定一个整数数组 nums,返回数组中可作为三角形三条边长度的三元组数量。三角形三条边需满足:任意两边之和大于第三边。 核心解题思路:排序 + 双指针三角形三边的核心条件是:两边之和大于第三边。对于排序后的数组,可简化为: 设三条边为 a ≤...
Leecode 0189. 轮转数组
189. 轮转数组给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 示例 1: 123456输入: nums = [1,2,3,4,5,6,7], k = 3输出: [5,6,7,1,2,3,4]解释:向右轮转 1 步: [7,1,2,3,4,5,6]向右轮转 2 步: [6,7,1,2,3,4,5]向右轮转 3 步: [5,6,7,1,2,3,4] 示例 2: 12345输入:nums = [-1,-100,3,99], k = 2输出:[3,99,-1,-100]解释: 向右轮转 1 步: [99,-1,-100,3]向右轮转 2 步: [3,99,-1,-100] 题目大意给定一个整数数组 nums 和非负整数 k,将数组元素向右轮转 k 个位置(即每个元素向右移动 k 位,末尾元素移动到开头)。要求尽可能优化时间和空间复杂度。 核心解题思路:三次反转法常规思路(如临时数组、多次右移)要么空间复杂度高(O (n)),要么时间复杂度高(O (nk))。三次反转法通过巧妙的反转操作,实现 O (n) 时间复杂度 + O (1)...
Leecode 0148. 排序链表
148. 排序链表给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 示例 1: 12输入:head = [4,2,1,3]输出:[1,2,3,4] 示例 2: 12输入:head = [-1,5,3,4,0]输出:[-1,0,3,4,5] 示例 3: 12输入:head = []输出:[] 题目大意给定链表的头节点 head,要求将链表按升序排列并返回排序后的链表头节点。 解题思路对于链表排序,最适合的高效算法是归并排序,原因如下: 归并排序的时间复杂度为 O (n log n),是链表排序的最优选择 链表的归并操作不需要像数组那样额外分配 O (n)...
Leecode 0086. Partition List
86. Partition ListGiven the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: 12Input: head = [1,4,3,2,5,2], x = 3Output: [1,2,2,4,3,5] Example 2: 12Input: head = [2,1], x = 2Output: [1,2] 题目大意给定链表的头节点 head 和一个值 x,要求将链表分隔成两部分:所有值小于 x 的节点排在所有值大于或等于 x...
Leecode 0082. Remove Duplicates from Sorted List II
82. Remove Duplicates from Sorted List IIGiven the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: 12Input: head = [1,2,3,3,4,4,5]Output: [1,2,5] Example 2: 12Input: head = [1,1,1,2,3]Output: [2,3] 题目大意给定一个已排序的链表,要求删除所有存在重复的节点(即重复的节点一个都不保留),仅保留原链表中只出现过一次的节点,最终返回排序后的新链表头节点。 核心解题思路由于链表已排序,重复节点必然相邻,因此可通过「遍历链表 + 跳过重复节点」的思路解决,关键是: 虚拟头节点:避免删除头节点时的特殊处理(如示例 2 中头节点...
Leecode 0287. Find the Duplicate Number
287. Find the Duplicate NumberGiven an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and using only constant extra space. Example 1: 12Input: nums = [1,3,4,2,2]Output: 2 Example 2: 12Input: nums = [3,1,3,4,2]Output: 3 Example 3: 12Input: nums = [3,3,3,3,3]Output: 3 题目大意给定一个包含 n + 1 个整数的数组 nums,其中每个整数都在...
Leecode 0151. Reverse Words in a String
151. Reverse Words in a StringGiven an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. Example 1: 12Input: s...
Leecode 0028. Find the Index of the First Occurrence in a String
28. Find the Index of the First Occurrence in a StringGiven two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: 1234Input: haystack = "sadbutsad", needle = "sad"Output: 0Explanation: "sad" occurs at index 0 and 6.The first occurrence is at index 0, so we return 0. Example 2: 123Input: haystack = "leetcode", needle = "leeto"Output: -1Explanation:...
Leecode 3002. Maximum Size of a Set After Removals
3002. Maximum Size of a Set After RemovalsYou are given two 0-indexed integer arrays nums1 and nums2 of even length n. You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals, you insert the remaining elements of nums1 and nums2 into a set s. Return the maximum possible size of the set s. Example 1: 1234Input: nums1 = [1,2,1,2], nums2 = [1,1,1,1]Output: 2Explanation: We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become...
Leecode 0454. 4Sum II
454. 4Sum IIGiven four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 Example 1: 123456Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]Output: 2Explanation:The two tuples are:1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2...
Leecode 0349. Intersection of Two Arrays
349. Intersection of Two ArraysGiven two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. Example 1: 12Input: nums1 = [1,2,2,1], nums2 = [2,2]Output: [2] Example 2: 123Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output: [9,4]Explanation: [4,9] is also accepted. 题目大意给定两个整数数组 nums1 和...
Leecode 0162. Find Peak Element
162. Find Peak Element题目A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example...
Leecode 0142. Linked List Cycle II
142. Linked List Cycle IIGiven the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. ...
Leecode 0019. Remove Nth Node From End of List
19. Remove Nth Node From End of ListGiven the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: 12Input: head = [1,2,3,4,5], n = 2Output: [1,2,3,5] Example 2: 12Input: head = [1], n = 1Output: [] Example 3: 12Input: head = [1,2], n = 1Output: [1] 题目大意给定一个链表的头节点,要求删除链表的倒数第 N 个节点,并返回删除后的链表头节点。 解题思路可以使用双指针法高效解决这个问题,只需一次遍历: 定义两个指针 fast 和 slow,初始都指向虚拟头节点 先让 fast 指针向前移动 N 步 然后让 fast 和 slow 同时向前移动,直到 fast 到达链表末尾 此时 slow...
Leecode 0707. Design Linked List
707. Design Linked ListDesign your implementation of the linked list. You can choose to use a singly or doubly linked list.A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. Implement the MyLinkedList...
Leecode 1201. Ugly Number III
1201. Ugly Number III题目Write a program to find the n-th ugly number. Ugly numbers are positive integers which are divisible by a or b or c. Example 1: Input: n = 3, a = 2, b = 3, c = 5 Output: 4 Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. Example 2: Input: n = 4, a = 2, b = 3, c = 4 Output: 6 Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6. Example 3: Input: n = 5, a = 2, b = 11, c = 13 Output: 10 Explanation: The ugly numbers are...
Leecode 0024. Swap Nodes in Pairs
24. Swap Nodes in PairsGiven a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3] Explanation: Example 2: Input: head = []$ Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1,2,3] Output: [2,1,3] 题目大意给定一个链表,要求两两交换相邻节点(如 1→2→3→4 变为...
Leecode 0074. 搜索二维矩阵
74. 搜索二维矩阵给你一个满足下述两条属性的 m x n 整数矩阵: 每行中的整数从左到右按非严格递增顺序排列。 每行的第一个整数大于前一行的最后一个整数。 给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。 示例 1: 12输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3输出:true 示例 2: 12输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13输出:false 解法1:二分查找由于矩阵具有特殊的有序性,可以将其视为一个有序的一维数组来处理: 整个矩阵可以看作是按行拼接而成的有序数组 使用二分查找高效定位目标值 通过计算将一维索引转换为二维矩阵的行和列 1234567891011121314151617181920212223242526272829303132class Solution {public: bool...
Leecode 0146. LRU Cache
146. LRU CacheDesign a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the...
Leecode 1089. Duplicate Zeros
1089. Duplicate Zeros题目Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function. Example 1: 123Input: [1,0,2,3,0,4,5,0]Output: nullExplanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] Example 2: 123Input:...
Leecode 0922. Sort Array By Parity II
922. Sort Array By Parity IIGiven an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: 123Input: nums = [4,2,5,7]Output: [4,5,2,7]Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: 12Input: nums = [2,3]Output: [2,3] 双指针解法: 初始化: 偶数索引指针 i 从 0 开始,每次移动 2...
Leecode 0977. Squares of a Sorted Array
977. Squares of a Sorted ArrayGiven an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: 12Input: [-4,-1,0,3,10]Output: [0,1,9,16,100] Example 2: 12Input: [-7,-3,2,3,11]Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing...
Leecode 0905. Sort Array By Parity
905. Sort Array By ParityGiven an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. Example 1: 123Input: nums = [3,1,2,4]Output: [2,4,3,1]Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Example 2: 12Input: nums = [0]Output: [0] 解法1:双指针12345678910111213141516class Solution{public: vector<int> sortArrayByParity(vector<int>...
Leecode 0904. Fruit Into Baskets
904. Fruit Into Baskets题目In a row of trees, the i-th tree produces fruit with type tree[i]. You start at any tree of your choice, then repeatedly perform the following steps: Add one piece of fruit from this tree to your baskets. If you cannot, stop. Move to the next tree to the right of the current tree. If there is no tree to the right, stop. Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then...
Leecode 0844. Backspace String Compare
844. Backspace String Compare题目Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: 123Input: S = "ab#c", T = "ad#c"Output: trueExplanation: Both S and T become "ac". Example 2: 123Input: S = "ab##", T = "c#d#"Output: trueExplanation: Both S and T become "". Example 3: 123Input: S = "a##c", T = "#a#c"Output: trueExplanation:...
Leecode 0704. Binary Search
704. Binary Search题目Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Note: You may assume that all elements in nums are...
Leecode 0509. Fibonacci Number
509. Fibonacci Number题目The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1. Given N, calculate F(N). Example 1: Input: 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: 4 Output: 3 Explanation: F(4)...
Leecode 0367. Valid Perfect Square
367. Valid Perfect Square题目Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false 完全平方数可以表示为连续奇数的和。 算法原理该算法利用了以下数学特性: 1 = 1(1²) 1 + 3 = 4(2²) 1 + 3 + 5 = 9(3²) 1 + 3 + 5 + 7 = 16(4²) 以此类推,n² = 1 + 3 + 5 + ... + (2n-1) 算法通过不断从目标数中减去连续的奇数(1, 3, 5, 7...),如果最终结果恰好为...
Leecode 0283. Move Zeroes
283. Move Zeroes题目Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example 1: 12Input: [0,1,0,3,12]Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. 解法1:双指针1234567891011121314151617181920class Solution {public: void moveZeroes(vector<int>& nums) { int n = nums.size(); int i = 0; //...
Leecode 0206. Reverse Linked List
206. Reverse Linked ListGiven the head of a singly linked list, reverse the list, and return the reversed list. Example 1: 12Input: head = [1,2,3,4,5]Output: [5,4,3,2,1] Example 2: 12Input: head = [1,2]Output: [2,1] Example 3: 12Input: head = []Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 解法 1:迭代解法123456789101112131415161718192021222324252627/** * Definition for singly-linked list. * struct ListNode { * int...
Leecode 0209. Minimum Size Subarray Sum
209. Minimum Size Subarray Sum题目Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example 1: 123Input: s = 7, nums = [2,3,1,2,4,3]Output: 2Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n)....
Leecode 0076. Minimum Window Substring
76. Minimum Window Substring题目Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: 12Input: S = "ADOBECODEBANC", T = "ABC"Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S. 题目大意给定一个源字符串 s,再给一个字符串...
Leecode 0105. Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal题目Given preorder and inorder traversal of a tree, construct the binary tree. **Note:**You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 题目大意根据一棵树的前序遍历与中序遍历构造二叉树。 注意:你可以假设树中没有重复的元素。 解题思路 inorder_map:用于快速查找中序遍历中元素对应的索引,时间复杂度 O...
Leecode 0162. Find Peak Element
162. Find Peak Element题目A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞. Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums =...
Leecode 0072. Edit Distance
72. Edit DistanceGiven two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: 123456Input: word1 = "horse", word2 = "ros"Output: 3Explanation: horse -> rorse (replace 'h' with 'r')rorse -> rose (remove 'r')rose -> ros (remove 'e') Example...
Leecode 0070. Climbing Stairs
70. Climbing Stairs题目You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1...
Leecode 0073. Set Matrix Zeroes
73. Set Matrix Zeroes题目Given an *m* x *n* matrix. If an element is 0, set its entire row and column to 0. Do it in-place. Follow up: A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? Example 1: 12Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]Output: [[1,0,1],[0,0,0],[1,0,1]] Example 2: 12Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]Output:...
Leecode 0035. Search Insert Position
35. Search Insert Position题目Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: 12Input: [1,3,5,6], 5Output: 2 Example 2: 12Input: [1,3,5,6], 2Output: 1 Example 3: 12Input: [1,3,5,6], 7Output: 4 Example 4: 12Input: [1,3,5,6], 0Output:...
Leecode 0069. Sqrt(x)
69. Sqrt(x)Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. Example 1: 123Input: x = 4Output: 2Explanation: The square root of 4 is 2, so we return 2. Example 2: 123Input: x = 8Output: 2Explanation: The square root of 8 is 2.82842..., and since we round it down to...
Leecode 0034. Find First and Last Position of Element in Sorted Array
34. Find First and Last Position of Element in Sorted Array题目Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] 查找第一个出现的位置: 当找到目标值时,不立即返回,而是继续向左查找(right...
Leecode 0027. Remove Element
27. Remove Element给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素。元素的顺序可能发生改变。然后返回 nums 中与 val 不同的元素的数量。 假设 nums 中不等于 val 的元素数量为 k,要通过此题,您需要执行以下操作: 更改 nums 数组,使 nums 的前 k 个元素包含不等于 val 的元素。nums 的其余元素和 nums 的大小并不重要。 返回 k。 用户评测: 评测机将使用以下代码测试您的解决方案: 123456789101112int[] nums = [...]; // 输入数组int val = ...; // 要移除的值int[] expectedNums = [...]; // 长度正确的预期答案。 // 它以不等于 val 的值排序。int k = removeElement(nums, val); // 调用你的实现assert k == expectedNums.length;sort(nums, 0, k); // 排序...
Leecode 0026. Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array给你一个 非严格递增排列 的数组 nums ,请你** 原地** 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。 考虑 nums 的唯一元素的数量为 k ,你需要做以下事情确保你的题解可以被通过: 更改数组 nums ,使 nums 的前 k 个元素包含唯一元素,并按照它们最初在 nums 中出现的顺序排列。nums 的其余元素与 nums 的大小不重要。 返回 k 。 判题标准: 系统会用下面的代码来测试你的题解: 123456789int[] nums = [...]; // 输入数组int[] expectedNums = [...]; // 长度正确的期望答案int k = removeDuplicates(nums); // 调用assert k == expectedNums.length;for (int i = 0; i < k; i++) { assert...
Leecode 0033. Search in Rotated Sorted Array
33. Search in Rotated Sorted Array题目Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums...
Leecode 0015. 3Sum
15. 3Sum题目Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: 1234567Given array nums = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]] 题目大意给定一个数组,要求在这个数组中找出 3 个数之和为 0 的所有组合。 解题思路用 map 提前计算好任意 2 个数字之和,保存起来,可以将时间复杂度降到...
Leecode 0017. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number题目Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: 12Input: "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although...
Leecode 0016. 3Sum Closest
16. 3Sum Closest题目Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: 123Given array nums = [-1, 2, 1, -4], and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 题目大意给定一个数组,要求在这个数组中找出 3 个数之和离 target 最近。 解题思路 初始值优化: 原代码中it初始化为...
Leecode 0011. Container With Most Water
11. Container With Most Water题目Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of...
Leecode 0014. Longest Common Prefix
14. Longest Common Prefix题目Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Constraints: 1 <= strs.length...
Leecode 0012. Integer to Roman
12. Integer to Roman题目Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 12345678Symbol ValueI 1V 5X 10L 50C 100D 500M 1000 For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from...
Leecode 0008. String to Integer (atoi)
8. String to Integer (atoi)题目Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is...
Leecode 0010. Regular Expression Matching
10. Regular Expression MatchingGiven an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example 1: 123Input: s = "aa", p = "a"Output: falseExplanation: "a" does not match the entire string "aa". Example...
Leecode 0009. Palindrome Number
9. Palindrome Number题目Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: 12Input: 121Output: true Example 2: 123Input: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: 123Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting...
Leecode 0004. Median of Two Sorted Arrays
4. Median of Two Sorted Arrays题目There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 题目大意给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m +...
Leecode 0007. Reverse Integer
7. Reverse Integer题目Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 **Note:**Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 题目大意给出一个 32 位的有符号整数,需要将这个整数中每位上的数字进行反转。注意:假设我们的环境只能存储得下 32...
Leecode 0005. Longest Palindromic Substring
5. Longest Palindromic Substring题目Given a string s, return the longest palindromic substring in s. Example 1: 1234Input: s = "babad"Output: "bab"Note: "aba" is also a valid answer. Example 2: 123Input: s = "cbbd"Output: "bb" Example 3: 123Input: s = "a"Output: "a" Example 4: 123Input: s = "ac"Output: "a" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters...
Leecode 0003. Longest Substring Without Repeating Characters
3. Longest Substring Without Repeating Characters题目Given a string, find the length of the longest substring without repeating characters. Example 1: 123Input: "abcabcbb"Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: 123Input: "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1. Example 3: 1234Input: "pwwkew"Output: 3Explanation: The answer is "wke", with the length of 3. ...
Leecode 0001.two sum
1. Two Sum题目Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: 1234Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1]. 题目大意在数组中找到两个数,它们的和等于给定的目标值 target,并返回这两个数在数组中的下标。要求每个元素只能使用一次,且保证有且仅有一个解。 解题思路方法一:双层循环(暴力枚举)思路 通过双重循环遍历数组中的每一对元素,检查它们的和是否等于目标值 target。外层循环控制第一个元素的索引...
Leecode 0002. Add Two Numbers
2. Add Two Numbers题目You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zeros, except the number 0 itself. Example 1: 123Input: l1 = [2,4,3], l2 = [5,6,4]Output: [7,0,8]Explanation: 342 + 465 = 807. Example 2: 12Input: l1 = [0], l2 = [0]Output: [0] Example...