Leetcode Detailed Solutions | Leetcode算法题解

By Long Luo

我的Leetcode的解题:


Chinese Solutions

Leetcode题目难度题解
1. 两数之和Easy2种方法:暴力 和 HashMap
2. 两数相加Medium2种方法:模拟 和 递归
4. 寻找两个正序数组的中位数Hard4种方法:合并数组,暴力法,二分搜索,划分数组
15. 三数之和Medium3种方法:暴力,Hash,双指针
18. 四数之和Medium4种方法:暴力,双指针,DFS,HashMap
22. 括号生成Medium2种方法:暴力法 和 回溯法
28. 实现 strStr()Easy理解KMP算法:从入门到推导
29. 两数相除Medium3种方法:暴力法,二分搜索,递归
42. 接雨水Hard5种解法:木桶原理,按行求,动态规划,双指针,单调栈
43. 字符串相乘Medium另辟蹊径,快速傅里叶变换(FFT)计算大数乘法
70. 爬楼梯Easy面试算法题:爬楼梯,N级楼梯有多少种走法?
148. 排序链表Medium4种方法:暴力,List,自顶向下归并排序,自底向上归并排序
155. 最小栈Easy3种方法:辅助栈,栈,链表
171. Excel 表列序号Easy仿照Excel的列编号,给定一个数字,输出该列编号字符串
209. 长度最小的子数组Medium5种方法:暴力,双指针,前缀和,前缀和 + 二分查找,二分查找
225. 用队列实现栈Easy如何改变队列元素顺序?
230. 二叉搜索树中第K小的元素Medium二叉搜索树中第K小的元素
232. 用栈实现队列Easy顺序翻转,使用两个栈:一个入队,一个出队
268. 丢失的数字Medium4种方法:排序,哈希表,异或,数学公式
299. 猜数字游戏Medium从遍历2次优化到遍历1次
318. 最大单词长度乘积Medium3种方法:从暴力状态压缩到位运算优化
384. 打乱数组Medium2种方法:暴力 和 洗牌算法
390. 消除游戏Medium经典算法:从约瑟夫问题说开去…
396. 旋转函数Medium3种方法:暴力法,动态规划,前缀和 + 滑动窗口
407. 接雨水 IIHard2种方法:优先队列存储每层围栏最低高度,BFS更新每个方块存水高度
超大数字的加减乘除 415. 字符串相加, 445. 两数相加 IIMedium超大数字的四则运算是如何实现的呢?
419. 甲板上的战舰Medium4种方法:一次遍历,DFS,统计战舰起点
423. 从英文中重建数字Medium找规律,依次确定数字的次数,逐步消元法
438. 找到字符串中所有字母异位词Medium滑动窗口:从HashMap,数组,再到统计字母数量之差
458. 可怜的小猪Hard从 经典面试问题 到 信息论
509. 斐波那契数Easy9种求斐波那契数(Fibonacci Numbers)的算法
519. 随机翻转矩阵Medium2种方法:暴力法 和 降维 + 哈希表
525. 连续数组Medium2种方法:暴力,前缀和 + 哈希表
559. N叉树的最大深度Easy3种方法:递归,DFS和BFS
594. 最长和谐子序列Easy4种方法:暴力枚举,排序 + 枚举,哈希表
598. 范围求和 IIEasy求所有操作的交集
686. 重复叠加字符串匹配Medium3种方法:暴力,字符串哈希,KMP
700. 二叉搜索树中的搜索Easy3种方法:递归,迭代,BFS
859. 亲密字符串Easy简单的字符串模拟
912. 排序数组Medium排序算法(Sorting Algorithms)
997. 找到小镇的法官Easy图论,计算各节点的入度和出度
1044. 最长重复子串Hard3种方法:从暴力到二分,二分搜索 + 字符串哈希,后缀数组
1218. 最长定差子序列Medium序列动态规划 + HashMap
1385. 两个数组间的距离值Easy2种方法:模拟 和 二分搜索
1705. 吃苹果的最大数目Medium贪心 + 优先队列:每天找最邻近过期的苹果吃
1816. 截断句子Easy3种方法:正则表达式,模拟和优化
meituan-002. 小美的仓库整理Medium记一道美团面试编程题的解题过程:从暴力到优化

English Solutions on My Website

Solutions on My Website.

Leetcode ProblemsDifficultySolutions
2. Add Two NumbersEasyJava Linkedlist Iteration and Recusion Solution
11. Container With Most WaterMedium2 Approaches: BF and Two Pointers with Image Explaination and Code Commented
17. Letter Combinations of a Phone NumberMedium4 Approaches: BF 4 Loops, Backtracking, BFS, Queue with Image Explaination
31. Next PermutationMediumTwo Pointers Solution with Detailed Explanation and Code Commented
34. Find First and Last Position of Element in Sorted ArrayMediumBinary Search Twice
36. Valid SudokuMedium2 Solutions Using HashSet + Array
39. Combination SumMediumThe Key of the Backtrack is Deduplicating and Pruning
50. Pow(x, n)MediumIllustration of Fast Power Algorithm - Exponentiation by Squaring or Binary Exponentiation
62. Unique PathsMedium3 Approaches: Dynamic Programming, Recursion, Math
69. Sqrt(x)Medium4 Approaches for Finding the Square Root of A Number: BF, Exponent, Binary Search and Newton Iteration Method
70. Climbing StairsEasy9 Fibonacci Algorithms: the Most Complete Solutions All In One
71. Simplify PathMediumjava/python/go Using Stack with Easy Detailed Explanations
74. Search a 2D MatrixMedium6 Approaches BF + 2D Coords + 2 Binary Search + 1 Binary Search + Row Scan
114. Flatten Binary Tree to Linked ListMediumRecursive Solution with 3-steps and Image Explanation
117. Populating Next Right Pointers in Each Node IIMedium3 Approaches: BFS, BFS + LinkedList, Recursion
120. TriangleMediumDP: Top-Down and Bottom-Up Approach
136. Single NumberEasy5 Lines Code / The XOR operator Cheatsheet / Bitwise Operation / with Easy Detailed Explanation
Binary and N-ary Tree Traversal: 144. Binary Tree Preorder TraversalEasyTree Traversals All In One: PreOrder, InOrder and PostOrder
167. Two Sum II - Input Array Is SortedMedium4 Approaches: Brute Force, HashMap, Binary Search, Two Pointers
171. Excel Sheet Column NumberEasyBase Conversion 2 Solutions: Left to Right and Right to Left
215. Kth Largest Element in an ArrayMedium3 Approaches: Sorting, Priority Queue, Divide and Conquer
216. Combination Sum IIIMedium2 Approaches: Backtracking and Bit Mask
219. Contains Duplicate IIEasy3 Solutions with Brute Force, HashMap and Sliding Window
240. Search a 2D Matrix IIMedium5 Approaches: BF, Binary Search(Row), Binary Search(Diagonal, Row, Col), Binary Search(Global), 2D Coord Axis
242. Valid AnagramEasy3 Solutions: HashMap, Sort and Count Count is the Fastest
287. Find the Duplicate NumberMedium9 Approaches: Count, Hash, Sort, Binary Search, Bit, Fast Slow Pointers
300. Longest Increasing SubsequenceMedium3 Approaches: Backtrack, DP, Binary Search
316. Remove Duplicate LettersMediumThe Detailed Explanation with 3-steps to Understand the Stack Solution Easy
329. Longest Increasing Path in a MatrixHard4 Approaches: BFS, Memory + DFS, DP, Topological Sorting
341. Flatten Nested List IteratorMedium2 Approaches: DFS, Iteration(Using Stack)
344. Reverse StringEasy2 Approaches: Two Pointers and Recursion
350. Intersection of Two Arrays IIEasy2 Solutions: Sort with Two Pointers and HashMap
372. Super PowMediumJava Fast Power Algorithm
377. Combination Sum IVMedium2 Approaches: Backtrack and DP with Follow Up Analysis
378. Kth Smallest Element in a Sorted MatrixMedium3 Approaches: Sorting, Merge Sort, Binary Search
399. Evaluate DivisionMedium4 Approaches: BFS, DFS, Floyd, Union Find
406. Queue Reconstruction by HeightMediumPattern of Data Pairs Problem: Sorting First then Greedy
440. K-th Smallest in Lexicographical OrderMedium
456. 132 PatternMedium6 Approaches: BF O(n^3), BF O(n^2), TreeMap, Monotonic Stack
509. Fibonacci NumberEasy9 Fibonacci Algorithms: the Most Complete Solutions All In One
617. Merge Two Binary TreesEasy4 Approaches: Recursion, BFS and DFS
763. Partition Labels)MediumIllustration of the Max Position of the Char in the Partition with Easy Detailed Explanation
856. Score of ParenthesesMedium5 Solutions from Beginner to Expert with Stack to O(1) Space Detailed Explanation
858. Mirror ReflectionMediumWhat If the Ray Not Reflected and Expand the Room with Image Explanation
881. Boats to Save PeopleMediumGreedy: Let the Heaviest match the lightest, if not matched, let it alone
895. Maximum Frequency StackHardThe Detailed Explanation using 2-Steps to Understand the HashMap + LinkedList Solution
991. Broken CalculatorMediumGreedy: Reverse Thinking with Binary Algorithm
946. Validate Stack SequencesMedium4 Solutions Using Array and Stack with Easy Detailed Explanation
1091. Shortest Path in Binary MatrixMediumWhy Use BFS? Search Every Possible Path vs Search A Possible Path
1249. Minimum Remove to Make Valid ParenthesesMediumUsing Stack with Easy Detailed Explanation of 2-steps Algorithm
1631. Path With Minimum EffortMedium3 Approaches: BFS(Dijkstra), Binary Search, Union Find
1642. Furthest Building You Can ReachMediumPriority Queue + Greedy: Consider Ladder as a One-time Unlimited Bricks
1721. Swapping Nodes in a Linked ListMedium3 Approaches: Swapping Values and Swapping Nodes with Image Explaination and Code Commented
1780. Check if Number is a Sum of Powers of ThreeEasy3 Solutions: Tricky, Recursive and Base 3 convertion
1834. Single-Threaded CPUMediumHow to Maintain the Enqueued Tasks? Sorting the array then Priority Queue

English Solutions on Leetcode

Solutions on Leetcode.

All code are in Github.


Leetcode ProblemsDifficultySolutions
2. Add Two NumbersEasy2 Approaches: Iteration and Recursion
3. Longest Substring Without Repeating CharactersEasyTwo Pointers: Sliding Window with HashSet
11. Container With Most WaterMedium2 Approaches: Brute Force and Two Pointers with Image Explanation
17. Letter Combinations of a Phone NumberMedium4 Approaches: BF 4 Loops, Backtracking, BFS, Queue with Image Explaination
19. Remove Nth Node From End of ListMedium3 Approaches: Brute Force, Stack, Slow Fast Pointers with Animation
21. Merge Two Sorted ListsEasyThe Recursive Algorithm with Detailed Image Explanation
29. Divide Two IntegersMedium5 Approaches: BF use Long, BF use Int, Binary Search use Long, Binary Search use Int and Recursion
31. Next PermutationMediumTwo Pointers Solution with Detailed Explanation and Code Commented
34. Find First and Last Position of Element in Sorted ArrayMediumBinary Search Twice
36. Valid SudokuMedium2 Approaches: HashSet and Array
39. Combination SumMediumEasy Backtracking Approach: Deduplicating and Pruning
42. Trapping Rain WaterHardFrom Brute Force to DP then Two Pointers with Detail Explaination
43. Multiply StringsMediumMath Geek: Fast Fourier Transform and Number Theoretic Transform
47. Permutations IIMediumPermutation Problems: Backtracking and Pruning
50. Pow(x, n)MediumFast Power Algorithm: Binary Exponentiation
55. Jump GameMediumLeetcode Jump Game Problems Series
62. Unique PathsMedium3 Approaches: DP, Recursion, Math
69. Sqrt(x)Medium4 Approaches: Brute Force, Exponent, Binary Search and the Newton Iteration Method
70. Climbing StairsEasy9 Fibonacci Algorithms: the Most Complete Solutions All In One
71. Simplify PathMediumStack Solution with Easy Detailed Explanation
74. Search a 2D MatrixMedium6 Approaches: Brute Force, Row Search, Column Search, One Binary Search, 2D Coordinate Axis
81. Search in Rotated Sorted Array IIMediumBinary Search: The Key is Narrow the Search Interval Step by Step
88. Merge Sorted ArrayEasy3 Approaches: Sorting, Two Pointers and Reverse Two Pointers
98. Validate Binary Search TreeMedium3 Approaches: Recursion, DFS and Iteration
102. Binary Tree Level Order TraversalMediumJava Simple BFS Solution
114. Flatten Binary Tree to Linked ListMediumImage Explanation to Understand the Recursion Solution
117. Populating Next Right Pointers in Each Node IIMedium3 Approaches: BFS, BFS + LinkedList, Recursion
118. Pascal’s TriangleEasyMath Intuition of Dynamic Programming: Shift One and Added
120. TriangleMediumDynamic Programming Space O(n) Solutions: Top-Down and Bottom-Up Approaches
125. Valid PalindromeEasySimple Two Pointers Solution
136. Single NumberEasyThe XOR Cheat Sheet and Bit Manipulation with Easy Detailed Explanation
Binary and N-ary Tree Traversal: 144. Binary Tree Preorder TraversalEasyTree Traversals All In One: PreOrder, InOrder and PostOrder
160. Intersection of Two Linked ListsEasy2 Approaches: HashSet and Two Pointers with Detailed Explanation
167. Two Sum II - Input Array Is SortedMedium4 Approaches: Brute Force, HashMap, Binary Search, Two Pointers
171. Excel Sheet Column NumberEasy2 Approaches: Base Conversion from High to Low and from Low to High
191. Number of 1 BitsEasy6 Approaches: Cycle, API, Divide and Conquer, Low Bit, Bit Set, Recursion
199. Binary Tree Right Side ViewMedium2 Approaches: DFS and BFS with Detailed Explanation
215. Kth Largest Element in an ArrayMedium3 Approaches: Sorting, Priority Queue, Divide and Conquer
216. Combination Sum IIIMedium2 Approaches: Backtracking and Bit Mask
219. Contains Duplicate IIEasy3 Approaches: Brute Force, HashMap and Sliding Window
240. Search a 2D Matrix IIMedium5 Approaches: Brute Force, Binary Search(Row), Binary Search(Diagonal, Row, Col), Binary Search(Global), 2D Coord Axis
242. Valid AnagramEasy3 Approaches: HashMap, Sorting and Counting
268. Missing NumberEasy4 Approaches: Sorting, Hash, XOR, Math
278. First Bad VersionEasyJava Binary Search Solution
287. Find the Duplicate NumberMedium9 Approaches:Brute Force, Count, Hash, In-place Marked, Sorting, Index Sort, Binary Search, Bit Manipulation, Fast Slow Pointers
295. Find Median from Data StreamMediumTwo Heaps with the Follow Up’s Solution
300. Longest Increasing SubsequenceMedium3 Approaches: Backtrack, DP, Binary Search
316. Remove Duplicate LettersMediumThe Detailed Explanation with 3-Steps to Understand the Stack Approach
322. Coin ChangeMedium3 Approaches: DFS, BFS, DP
329. Longest Increasing Path in a MatrixHard4 Approaches: BFS, Memory + DFS, DP, Topological Sorting
334. Increasing Triplet SubsequenceMediumWhy Greedy works?
341. Flatten Nested List IteratorMedium2 Approaches: DFS and Iteration(Using Stack)
342. Power of FourEasyJust One Line Code and Detailed Explanation
344. Reverse StringEasy2 Approaches: Two Pointers and Recursion
350. Intersection of Two Arrays IIEasy2 Approaches: Sorting with Two Pointers and HashMap
372. Super PowMedium2 Approaches: Brute Force and Binary Exponentiation
377. Combination Sum IVMedium2 Approaches: Backtrack and DP with Follow Up Analysis
378. Kth Smallest Element in a Sorted MatrixMedium3 Approaches: Sorting, Merge Sort, Binary Search
399. Evaluate DivisionMedium4 Approaches: BFS, DFS, Floyd, Union Find
406. Queue Reconstruction by HeightMediumPattern of Data Pairs Problem: Sorting First then Greedy
429. N-ary Tree Level Order TraversalMediumTraverse the Tree Level by Level: Standard BFS Solution
456. 132 PatternMedium4 Approaches: BF O(n^3), BF O(n^2), TreeMap, Monotonic Stack
509. Fibonacci NumberEasy9 Fibonacci Algorithms: the Most Complete Solutions All In One with Image Explanation
617. Merge Two Binary TreesEasy4 Approaches: Recursion, Iteration, BFS and DFS
658. Find K Closest ElementsMedium4 Approaches: Two Pointers, Sorting, Priority Queue and Binary Search
680. Valid Palindrome IIEasy3 Approaches: Brute Force, Recursion and Two Pointers
692. Top K Frequent WordsMedium2 Approaches: HashMap + Sort and Priority Queue
729. My Calendar IMedium3 Approaches: Brute Force, Binary Search, Segment Tree
746. Min Cost Climbing StairsEasyFibonacci Numbers: 9 Approaches: Recursion, DP, Math, Matrix
763. Partition LabelsMediumGreedy Solution with Easy Detailed Explanation
856. Score of ParenthesesMediumThe Tricky and Clean Solution: Replace Core by 1
858. Mirror ReflectionMediumWhat If the Ray Not Reflected and Expand the Room with Image Explanation
881. Boats to Save PeopleMediumGreedy: Let the Heaviest Match the Lightest, if Not Matched, Let it Alone
895. Maximum Frequency StackHardHashMap Solution with Detailed Explanation
923. 3Sum With MultiplicityMedium5 Approaches: BF, Three Pointers, TreeMap, Count, DP
946. Validate Stack SequencesMedium4 Approaches: Stack, Array, Greedy and O(n) Time O(1) Space
947. Most Stones Removed with Same Row or ColumnMediumIt is Literally a Graph: DFS and Union Find)
991. Broken CalculatorMediumGreedy: Reverse Thinking with Binary Algorithm
1029. Two City SchedulingMediumGreedy: Sorting the Costs Array by What?
1091. Shortest Path in Binary MatrixMediumWhy Use BFS? Search Every Possible Path vs Search A Possible Path
1137. N-th Tribonacci NumberEasyAny Language Beats 100% with Time O(1) Solution
1249. Minimum Remove to Make Valid ParenthesesMediumStack Solution with Easy Detailed Explanation
1302. Deepest Leaves SumMedium2 Approaches: BFS(Level Order Travesal) and DFS(Get Max Depth, then Traversal)
1631. Path With Minimum EffortMedium3 Approaches: BFS(Dijkstra), Binary Search, Union Find
1641. Count Sorted Vowel StringsMediumImage Explanation: Distributing N Balls into 5 Boxes, Some Boxes May Be Empty
1642. Furthest Building You Can ReachMediumPriority Queue + Greedy: Consider Ladder as a One-time Unlimited Bricks
1663. Smallest String With A Given Numeric ValueMediumGreedy O(n) Solution with Image Explaination
1721. Swapping Nodes in a Linked ListMedium3 Approaches: Swapping Values and Swapping Nodes with Image Explanation
1780. Check if Number is a Sum of Powers of ThreeEasy3 Approaches: Tricky, Recursive and Base 3 Conversion
1834. Single-Threaded CPUMediumHow to Maintain the Enqueued Tasks? Sorting the array then Priority Queue
2215. Find the Difference of Two ArraysEasyJava HashSet Solution
2475. Number of Unequal Triplets in ArrayEasyThe Fastest O(n) Solution: Math Combinations

All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗