├── .gitignore ├── Array.md ├── Design.md ├── Graph.md ├── Grokking the Coding Interview ├── Top 'K' Elements.md └── Topological Sort.md ├── Knapsack ├── CompletePack.cpp ├── Knapsack(compress).py ├── Knapsack.py └── 完全背包问题.md ├── LeetCode-Note.md ├── Ordered-Map.md ├── README.md ├── SQL Excercise ├── 175. Combine Two Tables.md ├── 181. Employees Earning More Than Their Managers.md ├── 183. Customers Who Never Order.md └── 197. Rising Temperature.md ├── String.md ├── binary-search.md ├── bit-manipulation.md ├── heap.md ├── images ├── DP-5.png ├── image-20200603194353694.png ├── merge-intervals-1.png ├── merge-intervals-2.png ├── merge-intervals-3.png └── two-pointers-1.png ├── merge-intervals.md ├── recursion-backtracking.md ├── sliding-window.md ├── stack.md ├── two-pointers.md ├── 剑指Offer ├── 剑指 Offer 12. 矩阵中的路径.md ├── 剑指 Offer 13. 机器人的运动范围.md └── 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面.md ├── 标点符号英语名称.md ├── 每日一题 ├── 1009. Complement of Base 10 Integer.md ├── 1010. Pairs of Songs With Total Durations Divisible by 60.md ├── 1015. Smallest Integer Divisible by K.md ├── 1023. Camelcase Matching.md ├── 1026. Maximum Difference Between Node and Ancestor.md ├── 1029. Two City Scheduling.md ├── 1032. Stream of Characters.md ├── 1041. Robot Bounded In Circle.md ├── 1071. Greatest Common Divisor of Strings.md ├── 1074. Number of Submatrices That Sum to Target.md ├── 1094. Car Pooling.md ├── 110. Balanced Binary Tree.md ├── 1103. Distribute Candies to People.md ├── 1143. Longest Common Subsequence.md ├── 1147. Longest Chunked Palindrome Decomposition.md ├── 1153. String Transforms Into Another String.md ├── 1155. Number of Dice Rolls With Target Sum.md ├── 1165. Single-Row Keyboard.md ├── 1198. Find Smallest Common Element in All Rows.md ├── 1222. Queens That Can Attack the King.md ├── 1249. Minimum Remove to Make Valid Parentheses.md ├── 1257. Smallest Common Region.md ├── 1272. Remove Interval.md ├── 1291. Sequential Digits.md ├── 1302. Deepest Leaves Sum.md ├── 1312. Minimum Insertion Steps to Make a String Palindrome.md ├── 1316. Distinct Echo Substrings.md ├── 1329. Sort the Matrix Diagonally.md ├── 133. Clone Graph.md ├── 1332. Remove Palindrome Subsequences.md ├── 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.md ├── 1335. Minimum Difficulty of a Job Schedule (DP-hard).md ├── 1337. The K Weakest Rows in a Matrix.md ├── 135. Candy(hard).md ├── 139. Word Break.md ├── 1396. Design Underground System.md ├── 1413. Minimum Value to Get Positive Step by Step Sum.md ├── 1423. Maximum Points You Can Obtain from Cards.md ├── 1437. Check If All 1's Are at Least Length K Places Away.md ├── 1446. Consecutive Characters.md ├── 147. Insertion Sort List.md ├── 1481. Least Number of Unique Integers after K Removals.md ├── 1503. Last Moment Before All Ants Fall Out of a Plank.md ├── 1504.CountSubmatricesWithAllOnes.md ├── 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits.md ├── 1506. Find Root of N-Ary Tree.md ├── 1510. Stone Game IV.md ├── 1524. Number of Sub-arrays With Odd Sum.md ├── 1537. Get the Maximum Score.md ├── 155. Min Stack.md ├── 1551. Minimum Operations to Make Array Equal.md ├── 1566. Detect Pattern of Length M Repeated K or More Times.md ├── 161. One Edit Distance.md ├── 1631. Path With Minimum Effort.md ├── 1636. Sort Array by Increasing Frequency (easy).md ├── 164. Maximum Gap (Hard).md ├── 1640. Check Array Formation Through Concatenation.md ├── 1641. Count Sorted Vowel Strings.md ├── 1646. Get Maximum in Generated Array.md ├── 165. Compare Version Numbers.md ├── 1657. Determine if Two Strings Are Close.md ├── 1658. Minimum Operations to Reduce X to Zero.md ├── 1662. Check If Two String Arrays are Equivalent.md ├── 1663. Smallest String With A Given Numeric Value.md ├── 1679. Max Number of K-Sum Pairs.md ├── 168. Excel Sheet Column Title.md ├── 1694. Reformat Phone Number.md ├── 1703. Minimum Adjacent Swaps for K Consecutive Ones (Hard).md ├── 1706. Where Will the Ball Fall.md ├── 1713. Minimum Operations to Make a Subsequence.md ├── 1717. Maximum Score From Removing Substrings.md ├── 1718. Construct the Lexicographically Largest Valid Sequence.md ├── 1721. Swapping Nodes in a Linked List.md ├── 1723. Find Minimum Time to Finish All Jobs.md ├── 1725. Number Of Rectangles That Can Form The Largest Square.md ├── 1727. Largest Submatrix With Rearrangements.md ├── 1730. Shortest Path to Get Food.md ├── 1740. Find Distance in a Binary Tree.md ├── 1743. Restore the Array From Adjacent Pairs.md ├── 1745. Palindrome Partitioning IV.md ├── 1755. Closest Subsequence Sum.md ├── 1758. Minimum Changes To Make Alternating Binary String.md ├── 1760. Minimum Limit of Balls in a Bag.md ├── 1761. Minimum Degree of a Connected Trio in a Graph.md ├── 1762. Buildings With an Ocean View.md ├── 1763. Longest Nice Substring.md ├── 1764. Form Array by Concatenating Subarrays of Another Array.md ├── 1765. Map of Highest Peak.md ├── 1786. Number of Restricted Paths From First to Last Node.md ├── 179. Largest Number.md ├── 1792. Maximum Average Pass Ratio.md ├── 1799. Maximize Score After N Operations.md ├── 1801. Number of Orders in the Backlog.md ├── 1816. Truncate Sentence.md ├── 1817. Finding the Users Active Minutes.md ├── 1822. Sign of the Product of an Array.md ├── 1827. Minimum Operations to Make the Array Increasing.md ├── 1832. Check if the Sentence Is Pangram.md ├── 1837. Sum of Digits in Base K.md ├── 1844. Replace All Digits with Characters.md ├── 1848. Minimum Distance to the Target Element.md ├── 1849. Splitting a String Into Descending Consecutive Values.md ├── 1852. Distinct Numbers in Each Subarray.md ├── 1854. Maximum Population Year.md ├── 1855. Maximum Distance Between a Pair of Values.md ├── 1856. Maximum Subarray Min-Product.md ├── 1858. Longest Word With All Prefixes.md ├── 1859. Sorting the Sentence.md ├── 1863. Sum of All Subset XOR Totals.md ├── 1869. Longer Contiguous Segments of Ones than Zeros.md ├── 187. Repeated DNA Sequences.md ├── 1870. Minimum Speed to Arrive on Time.md ├── 1871. Jump Game VII.md ├── 1880. Check if Word Equals Summation of Two Words.md ├── 1881. Maximum Value after Insertion.md ├── 19. Remove Nth Node From End of List.md ├── 191. Number of 1 Bits.md ├── 199. Binary Tree Right Side View.md ├── 2. Add Two Numbers.md ├── 20. Valid Parentheses.md ├── 2000. Reverse Prefix of Word.md ├── 2011. Final Value of Variable After Performing Operations.md ├── 2016. Maximum Difference Between Increasing Elements.md ├── 2032. Two Out of Three.md ├── 2042. Check if Numbers Are Ascending in a Sentence.md ├── 205. Isomorphic Strings.md ├── 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points.md ├── 21. Merge Two Sorted Lists.md ├── 216. Combination Sum III.md ├── 22. Generate Parentheses.md ├── 2216. Minimum Deletions to Make Array Beautiful.md ├── 228. Summary Ranges.md ├── 234. Palindrome Linked List.md ├── 240. Search a 2D Matrix II.md ├── 243. Shortest Word Distance.md ├── 244. Shortest Word Distance II.md ├── 246. Strobogrammatic Number.md ├── 261. Graph Valid Tree.md ├── 268. Missing Number.md ├── 285. Inorder Successor in BST.md ├── 287. Find the Duplicate Numeber.md ├── 290. Word Pattern.md ├── 295. Find Median from Data Stream.md ├── 301. Remove Invalid Parentheses.md ├── 316. Remove Duplicate Letters.md ├── 32. Longest Valid Parentheses.md ├── 321. Create Maximum Number.md ├── 323. Number of Connected Components in an Undirected Graph.md ├── 329. Longest Increasing Path in a Matrix.md ├── 337. House Robber III.md ├── 339. Nested List Weight Sum.md ├── 347. Top K Frequent Elements.md ├── 354. Russian Doll Envelopes - Java.md ├── 354. Russian Doll Envelopes.md ├── 362. Design Hit Counter.md ├── 364. Nested List Weight Sum II.md ├── 376. Wiggle Subseqeunce.md ├── 392. Is Subsequence.md ├── 402. Remove K Digits.md ├── 403. Frog Jump (Hard).md ├── 406. Queue Reconstruction by Height.md ├── 409. Longest Palindrome.md ├── 41. First Missing Positive.md ├── 410. Split Array Largest Sum (Hard).md ├── 413. Arithmetic Slices.md ├── 416. Partition Equal Subset Sum.md ├── 417. Pacific Atlantic Water Flow.md ├── 42. Trapping Rain Water.md ├── 421. Maximum XOR of Two Numbers in an Array.md ├── 431. Encode N-ary Tree to Binary Tree (Hard).md ├── 434. Number of Segments in a String.md ├── 436. Find Right Interval.md ├── 449. Serialize and Deserialize BST.md ├── 45.JumpGameII.md ├── 450. Delete Node in a BST(Java).md ├── 450. Delete Node in a BST.md ├── 456. 132 Pattern.md ├── 458. Poor Pigs (Hard).md ├── 459. Repeated Substring Pattern.md ├── 468. Validate IP Address.md ├── 470. Implement Rand10() Using Rand7().md ├── 472. Concatenated Words.md ├── 474. Ones and Zeroes.md ├── 482.LicenseKeyFormatting.md ├── 489. Robot Room Cleaner (Hard).md ├── 495. Teemo Attacking.md ├── 498. Diagonal Traverse.md ├── 5. Longest Palindromic Substring.md ├── 510. In-order Successor in BST II.md ├── 516. Longest Palindromic Subsequence.md ├── 521. Longest Uncommon Subsequence I.md ├── 522. Longest Uncommon Subsequence II.md ├── 524. Longest Word in Dictionary through Deleting.md ├── 526. Beautiful Arrangement.md ├── 532. K-diff Pairs in an Array.md ├── 538. Convert BST to Greater Tree.md ├── 542. 01 Matrix.md ├── 556. Next Greater Element III.md ├── 563. Binary Tree Tilt.md ├── 575. Distribute Candies.md ├── 576. Out of Boundary Paths.md ├── 581. Shortest Unsorted Continous Subarray.md ├── 582. Kill Process.md ├── 593. Valid Square.md ├── 594. Longest Harmonious Subsequence.md ├── 621. Task Scheduler.md ├── 622. Design Circular Queue.md ├── 623. Add One Row to Tree.md ├── 624. Maximum Distance in Arrays.md ├── 637. Average of Levels in Binary Tree.md ├── 645. Set Mismatch.md ├── 647. Palindromic Substrings.md ├── 661. Image Smoother.md ├── 662. Maximum Width of Binary Tree.md ├── 670. Maximum Swap.md ├── 671. Second Minimum Node In a Binary Tree.md ├── 673. Number of Longest Increasing Subsequence.md ├── 679. 24 Game.md ├── 680. Valid Palindrome II.md ├── 692. Top K Frequent Words.md ├── 693. Binary Number with Alternating Bits.md ├── 698. Partition to K Equal Sum Subsets.md ├── 701. Insert into a Binary Search Tree.md ├── 702. Search in a Sorted Array of Unknown Size.md ├── 705. Design HashSet.md ├── 706. Design HashMap.md ├── 708. Insert into a Sorted Circular Linked List.md ├── 71. Simplify Path.md ├── 712. Minimum ASCII Delete Sum for Two Strings.md ├── 714. Best Time to Buy and Sell Stock with Transaction Fee.md ├── 718. Maximum Length of Repeated Subarray.md ├── 735. Asteroid Collision.md ├── 739. Daily Temperatures.md ├── 743. Network Delay Time.md ├── 759. Employee Free Time.md ├── 763. Partition Labels.md ├── 784. Letter Case Permutation.md ├── 799. Champagne Tower.md ├── 804. Unique Morse Code Words.md ├── 81. Search in Rotated Sorted Array II.md ├── 82. Remove Duplicates from Sorted List II.md ├── 821. Shortest Distance to a Character.md ├── 824. Goat Latin (easy).md ├── 828. Count Unique Characters of All Substrings.md ├── 83. 删除有序链表中的重复元素.md ├── 831. Masking Personal Information.md ├── 832. Flipping an Image.md ├── 841. Keys and Rooms.md ├── 844. Backspace String Compare.md ├── 845. Longest Mountain in Array.md ├── 849. Maximize Distance to Closest Person.md ├── 85. Maximum Rectangle.md ├── 856. Score of Parentheses.md ├── 86. Partition List.md ├── 863. All Nodes Distance K in Binary Tree.md ├── 870. Advantage Shuffle.md ├── 88. Merge Sorted Array.md ├── 880. Decoded String at Index.md ├── 881. Boats to Save People.md ├── 883. Projection Area of 3D Shapes.md ├── 887. Super Egg Drop.md ├── 895. Maximum Frequency Stack.md ├── 897. Increasing Order Search Tree.md ├── 902. Numbers At Most N Given Digit Set.md ├── 905. Sort Array By Parity.md ├── 91. Decode Ways.md ├── 910. Smallest Range II.md ├── 915. Partition Array into Disjoint Intervals.md ├── 916. Word Subsets.md ├── 92. Reverse Linked List II.md ├── 929.UniqueEmailAddresses.md ├── 934. Shortest Bridge.md ├── 938. Range Sum of BST.md ├── 946. Validate Stack Sequences.md ├── 948. Bag of Tokens.md ├── 952. Largest Component Size by Common Factor (Hard).md ├── 967. Numbers With Same Consecutive Differences.md ├── 97. Interleaving String (hard).md ├── 974. Subarray Sums Divisible by K.md ├── 980. Unique Paths III (Hard).md ├── 987. Vertical Order Traversal of a Binary Tree.md ├── 99. Recover Binary Search Tree.md ├── 991. Broken Calculator.md ├── Acwing 1455. 招聘.md ├── BinarySearch.java ├── src │ ├── 1413.java │ └── 495.java ├── template.md ├── 【Day 01】 2020-06-01 - 66. 加一.md ├── 【Day 02】 2020-06-02 - 75. 颜色分类.md ├── 【Day 03】 2020-06-03 - 1381. 设计一个支持增量操作的栈.md ├── 【Day 04】 2020-06-04 - 394. 字符串解码.md ├── 【Day 05】 2020-06-05 - 232. 用栈实现队列.md ├── 【Day 06】 2020-06-06 - 380. 常数时间插入、删除和获取随机元素.md ├── 【Day 07】 2020-06-07 - 206. 反转链表.md ├── 【Day 08】 2020-06-07 - 430. 扁平化多级双向链表.md ├── 【Day 09】 2020-06-09 - 109. 有序链表转换二叉搜索树.md ├── 【Day 10】 2020-06-10 - 160. 相交链表.md ├── 【Day 11】 2020-06-11 - 142. 环形链表 II.md ├── 【Day 12】- 146. LRU缓存机制.md ├── 【Day 13】- 104. 二叉树的最大深度.md ├── 【Day 14】- 100. 相同的树.md ├── 【Day 15】- 129. 求根到叶子节点数字之和.md ├── 【Day 16】- 513. 找树左下角的值.md ├── 【Day 17】- 105. 从前序与中序遍历序列构造二叉树.md ├── 【Day 18】 - 124. 二叉树中的最大路径和.md ├── 【Day19】- 1. 两数之和.md ├── 【Day20】 - 447. 回旋镖的数量.md ├── 【Day21】- 36. 有效的数独.md ├── 【Day22】- 645. 错误的集合.md ├── 【Day23】- 面试题04.01. 节点间通路.md ├── 【Graph】Course Schedule.md ├── 牛客网 - 迷宫寻路.md └── 鸡蛋硬度.md └── 算法模板代码 ├── 1091. Shortest Path in Binary Matrix.md ├── Combination Sum等.md ├── Dijkstra-堆优化.md ├── Trie 前缀树.md ├── acw_Java.java ├── spfa 求最短路.md ├── 二分查找.md ├── 单链表-数组写法.md ├── 单链表.java ├── 单链表的快速排序.md ├── 双链表.java ├── 字符串哈希.java ├── 并查集.java ├── 归并排序.java ├── 快速排序.java ├── 最大矩形.java ├── 最大连续子数组的和.md ├── 最长上升公共子序列.md ├── 最长连续不重复的子序列.md ├── 朴素Dijkstra.md ├── 树状数组.md ├── 模拟散列表.java ├── 牛客OJ.java ├── 直方图最大面积.java └── 股票买卖汇总.md /Knapsack/CompletePack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int N = 1010; 7 | 8 | int n, m; 9 | int v[N], w[N]; 10 | int f[N][N]; 11 | 12 | int main() 13 | { 14 | cin >> n >> m; 15 | for (int i = 1; i <= n; i++) 16 | cin >> v[i] >> w[i]; 17 | for (int i = 1; i <= n; i ++) 18 | for (int j = 1; j <= m; j ++) 19 | { 20 | f[i][j] = f[i-1][j]; 21 | if (j >= v[i]) 22 | f[i][j] = max(f[i][j], f[i][j-v[i]] + w[i]); 23 | } 24 | cout << f[n][m] << endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Knapsack/Knapsack(compress).py: -------------------------------------------------------------------------------- 1 | ''' 2 | 路径压缩DP 3 | ''' 4 | 5 | def solve_knapsack(profits, weights, capacity): 6 | # basic check 7 | n = len(profits) 8 | if capacity <= 0 or n == 0 or len(weights) != n: 9 | return 0 10 | 11 | # DEFINE dp[index][capacity+1] 12 | dp = [[0 for x in range(capacity + 1)] for y in range(2)] 13 | 14 | # IF WE HAVE ONLY ONE WEIGHT, WE WILL TAKE IT IF IT IS NOT MORE THAN THE CAPACITY 15 | for c in range(0, capacity + 1): 16 | if weights[0] <= c: 17 | dp[0][c] = dp[1][c] = profits[0] 18 | 19 | # PROCESS ALL SUB-ARRAYS FOR ALL THE CAPACITIES 20 | for idx in range(1, n): 21 | for c in range(0, capacity + 1): 22 | pf1, pf2 = 0, 0 23 | pf1 = profits[idx] + dp[(idx - 1) % 2][c - weights[idx]] if weights[idx] <= c else pf1 24 | pf2 = dp[(idx - 1) % 2][c] 25 | dp[idx % 2][c] = max(pf1, pf2) 26 | 27 | return dp[(n - 1) % 2][capacity] 28 | 29 | 30 | def main(): 31 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=5)) 32 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=6)) 33 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=7)) 34 | 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /Knapsack/Knapsack.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This means that dp[i][c] will represent the maximum knapsack profit for capacity ‘c’ calculated from the first ‘i’ items. 3 | ''' 4 | 5 | 6 | def solve_knapsack(profits, weights, capacity): 7 | # basic check 8 | n = len(profits) 9 | if capacity <= 0 or n == 0 or len(weights) != n: 10 | return 0 11 | 12 | # DEFINE dp[index][capacity+1] 13 | dp = [[0 for x in range(capacity + 1)] for y in range(n)] 14 | 15 | for i in range(0, n): 16 | dp[i][0] = 0 17 | 18 | # IF WE HAVE ONLY ONE WEIGHT, WE WILL TAKE IT IF IT IS NOT MORE THAN THE CAPACITY 19 | for c in range(0, capacity + 1): 20 | if weights[0] <= c: 21 | dp[0][c] = profits[0] 22 | 23 | # PROCESS ALL SUB-ARRAYS FOR ALL THE CAPACITIES 24 | for idx in range(1, n): 25 | for c in range(1, capacity + 1): 26 | pf1, pf2 = 0, 0 27 | pf1 = profits[idx] + dp[idx - 1][c - weights[idx]] if weights[idx] <= c else pf1 28 | pf2 = dp[idx - 1][c] 29 | dp[idx][c] = max(pf1, pf2) 30 | 31 | return dp[n - 1][capacity] 32 | 33 | 34 | def main(): 35 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=5)) 36 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=6)) 37 | print(solve_knapsack(profits=[1, 6, 10, 16], weights=[1, 2, 3, 5], capacity=7)) 38 | 39 | 40 | main() 41 | -------------------------------------------------------------------------------- /Knapsack/完全背包问题.md: -------------------------------------------------------------------------------- 1 | ## 完全背包问题 2 | 3 | https://www.acwing.com/problem/content/3/ 4 | 5 | 有 N 种物品和一个容量是 V 的背包,每种物品都有**无限件**可用。 6 | 7 | 第 i 种物品的体积是 vi,价值是 wi。 8 | 9 | 求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。 10 | 输出最大价值。 11 | 12 | **输入格式** 13 | 第一行两个整数,N,V,用空格隔开,分别表示物品种数和背包容积。 14 | 15 | 接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 种物品的体积和价值。 16 | 17 | **输出格式** 18 | 输出一个整数,表示最大价值。 19 | 20 | **数据范围** 21 | 0 46 | #include 47 | 48 | using namespace std; 49 | 50 | const int N = 1010; 51 | 52 | int n, m; 53 | int v[N], w[N]; 54 | int f[N][N]; 55 | 56 | int main() 57 | { 58 | cin >> n >> m; 59 | for (int i = 1; i <= n; i++) 60 | cin >> v[i] >> w[i]; 61 | for (int i = 1; i <= n; i ++) 62 | for (int j = 1; j <= m; j ++) 63 | { 64 | f[i][j] = f[i-1][j]; 65 | if (j >= v[i]) 66 | f[i][j] = max(f[i][j], f[i][j-v[i]] + w[i]); 67 | } 68 | cout << f[n][m] << endl; 69 | 70 | return 0; 71 | } 72 | ``` 73 | 74 | - 压缩状态为**一维**(优化,对上述代码的等价变形) 75 | 76 | ```cpp 77 | #include 78 | #include 79 | 80 | using namespace std; 81 | 82 | const int N = 1010; 83 | 84 | int n, m; 85 | int v[N], w[N]; 86 | int f[N]; 87 | 88 | int main() 89 | { 90 | cin >> n >> m; 91 | for (int i = 1; i <= n; i++) 92 | cin >> v[i] >> w[i]; 93 | for (int i = 1; i <= n; i ++) 94 | for (int j = v[i]; j <= m; j ++) 95 | { 96 | f[j] = max(f[j], f[j-v[i]] + w[i]); 97 | } 98 | cout << f[m] << endl; 99 | 100 | return 0; 101 | } 102 | ``` 103 | 104 | -------------------------------------------------------------------------------- /Ordered-Map.md: -------------------------------------------------------------------------------- 1 | # Ordered Map 2 | 3 | ## 220. Contains Duplicate III 4 | 5 | https://leetcode.com/problems/contains-duplicate-iii/ 6 | 7 | Given an array of integers, find out whether there are two distinct indices *i* and *j* in the array such that the **absolute** difference between **nums[i]** and **nums[j]** is at most *t* and the **absolute** difference between *i* and *j* is at most *k*. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: nums = [1,2,3,1], k = 3, t = 0 13 | Output: true 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: nums = [1,0,1,1], k = 1, t = 2 20 | Output: true 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: nums = [1,5,9,1,5,9], k = 2, t = 3 27 | Output: false 28 | ``` 29 | 30 | ### 代码 31 | 32 | ```python 33 | class Solution: 34 | def containsNearbyAlmostDuplicate(self, nums, k, t): 35 | if t < 0: return False 36 | n = len(nums) 37 | d = {} 38 | w = t + 1 39 | for i in range(n): 40 | m = nums[i] // w 41 | if m in d: 42 | return True 43 | if m - 1 in d and abs(nums[i] - d[m - 1]) < w: 44 | return True 45 | if m + 1 in d and abs(nums[i] - d[m + 1]) < w: 46 | return True 47 | d[m] = nums[i] 48 | if i >= k: del d[nums[i - k] // w] 49 | return False 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /SQL Excercise/175. Combine Two Tables.md: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/combine-two-tables/ 2 | ``` 3 | Table: Person 4 | 5 | +-------------+---------+ 6 | | Column Name | Type | 7 | +-------------+---------+ 8 | | PersonId | int | 9 | | FirstName | varchar | 10 | | LastName | varchar | 11 | +-------------+---------+ 12 | PersonId is the primary key column for this table. 13 | Table: Address 14 | 15 | +-------------+---------+ 16 | | Column Name | Type | 17 | +-------------+---------+ 18 | | AddressId | int | 19 | | PersonId | int | 20 | | City | varchar | 21 | | State | varchar | 22 | +-------------+---------+ 23 | AddressId is the primary key column for this table. 24 | 25 | 26 | Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people: 27 | 28 | FirstName, LastName, City, State 29 | ``` 30 | ### Answer 31 | 32 | ```mysql 33 | # Write your MySQL query statement below 34 | select FirstName, LastName, City, State 35 | from 36 | Person left join Address 37 | on 38 | Person.PersonId = Address.PersonID 39 | ``` 40 | -------------------------------------------------------------------------------- /SQL Excercise/181. Employees Earning More Than Their Managers.md: -------------------------------------------------------------------------------- 1 | ## 181. Employees Earning More Than Their Managers 2 | 3 | https://leetcode.com/problems/employees-earning-more-than-their-managers/ 4 | 5 | The `Employee` table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. 6 | 7 | ``` 8 | +----+-------+--------+-----------+ 9 | | Id | Name | Salary | ManagerId | 10 | +----+-------+--------+-----------+ 11 | | 1 | Joe | 70000 | 3 | 12 | | 2 | Henry | 80000 | 4 | 13 | | 3 | Sam | 60000 | NULL | 14 | | 4 | Max | 90000 | NULL | 15 | +----+-------+--------+-----------+ 16 | ``` 17 | 18 | Given the `Employee` table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. 19 | 20 | ``` 21 | +----------+ 22 | | Employee | 23 | +----------+ 24 | | Joe | 25 | +----------+ 26 | ``` 27 | 28 | ### 代码 29 | 30 | ```mysql 31 | # Write your MySQL query statement below 32 | select e1.Name as Employee 33 | from 34 | Employee e1 left join Employee e2 35 | on 36 | e1.ManagerId = e2.id 37 | where 38 | e1.Salary > e2.Salary 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /SQL Excercise/183. Customers Who Never Order.md: -------------------------------------------------------------------------------- 1 | ## 183. Customers Who Never Order 2 | 3 | https://leetcode.com/problems/customers-who-never-order/ 4 | 5 | Suppose that a website contains two tables, the `Customers` table and the `Orders` table. Write a SQL query to find all customers who never order anything. 6 | 7 | Table: `Customers`. 8 | 9 | ``` 10 | +----+-------+ 11 | | Id | Name | 12 | +----+-------+ 13 | | 1 | Joe | 14 | | 2 | Henry | 15 | | 3 | Sam | 16 | | 4 | Max | 17 | +----+-------+ 18 | ``` 19 | 20 | Table: `Orders`. 21 | 22 | ``` 23 | +----+------------+ 24 | | Id | CustomerId | 25 | +----+------------+ 26 | | 1 | 3 | 27 | | 2 | 1 | 28 | +----+------------+ 29 | ``` 30 | 31 | Using the above tables as example, return the following: 32 | 33 | ``` 34 | +-----------+ 35 | | Customers | 36 | +-----------+ 37 | | Henry | 38 | | Max | 39 | +-----------+ 40 | ``` 41 | 42 | ### 代码 43 | 44 | ```mysql 45 | # Write your MySQL query statement below 46 | select Customers.Name as "Customers" from Customers where Customers.Id not in(select CustomerId from Orders) 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /SQL Excercise/197. Rising Temperature.md: -------------------------------------------------------------------------------- 1 | ## 197. Rising Temperature 2 | 3 | https://leetcode.com/problems/rising-temperature/ 4 | 5 | Table: `Weather` 6 | 7 | ``` 8 | +---------------+---------+ 9 | | Column Name | Type | 10 | +---------------+---------+ 11 | | id | int | 12 | | recordDate | date | 13 | | temperature | int | 14 | +---------------+---------+ 15 | id is the primary key for this table. 16 | This table contains information about the temperature in a certain day. 17 | ``` 18 | 19 | 20 | 21 | Write an SQL query to find all dates' `id` with higher temperature compared to its previous dates (yesterday). 22 | 23 | Return the result table in **any order**. 24 | 25 | The query result format is in the following example: 26 | 27 | ``` 28 | Weather 29 | +----+------------+-------------+ 30 | | id | recordDate | Temperature | 31 | +----+------------+-------------+ 32 | | 1 | 2015-01-01 | 10 | 33 | | 2 | 2015-01-02 | 25 | 34 | | 3 | 2015-01-03 | 20 | 35 | | 4 | 2015-01-04 | 30 | 36 | +----+------------+-------------+ 37 | 38 | Result table: 39 | +----+ 40 | | id | 41 | +----+ 42 | | 2 | 43 | | 4 | 44 | +----+ 45 | In 2015-01-02, temperature was higher than the previous day (10 -> 25). 46 | In 2015-01-04, temperature was higher than the previous day (30 -> 20). 47 | ``` 48 | 49 | ### 代码 50 | 51 | ```mysql 52 | SELECT w1.Id 53 | FROM 54 | Weather w1 LEFT JOIN 55 | Weather w2 56 | ON DATEDIFF(w1.RecordDate,w2.RecordDate) = 1 57 | WHERE 58 | w1.Temperature > w2.Temperature 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /images/DP-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/DP-5.png -------------------------------------------------------------------------------- /images/image-20200603194353694.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/image-20200603194353694.png -------------------------------------------------------------------------------- /images/merge-intervals-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/merge-intervals-1.png -------------------------------------------------------------------------------- /images/merge-intervals-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/merge-intervals-2.png -------------------------------------------------------------------------------- /images/merge-intervals-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/merge-intervals-3.png -------------------------------------------------------------------------------- /images/two-pointers-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LLancelot/LeetCode/0be0dc0d9a01fb974e68856a1f103035a9e7413d/images/two-pointers-1.png -------------------------------------------------------------------------------- /剑指Offer/剑指 Offer 13. 机器人的运动范围.md: -------------------------------------------------------------------------------- 1 | ## 剑指 Offer 13. 机器人的运动范围 2 | 3 | https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/ 4 | 5 | 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子? 6 | 7 | 8 | 9 | > 示例 1: 10 | > 11 | > 输入:m = 2, n = 3, k = 1 12 | > 输出:3 13 | > 14 | > 15 | > 16 | > 示例 2: 17 | > 18 | > 输入:m = 3, n = 1, k = 0 19 | > 输出:1 20 | > 21 | > 22 | > 23 | > 提示: 24 | > 25 | > 1 <= n,m <= 100 26 | > 0 <= k <= 20 27 | > 28 | > 29 | > 30 | > 来源:力扣(LeetCode) 31 | > 链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof 32 | > 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 33 | 34 | 35 | 36 | ### 代码 37 | 38 | ```java 39 | class Solution { 40 | public int[] dirs = {1, 0, -1, 0, 1}; 41 | public boolean[][] visited; 42 | public int m, n, k; 43 | public int movingCount(int _m, int _n, int _k) { 44 | m = _m; 45 | n = _n; 46 | k = _k; 47 | visited = new boolean[m][n]; 48 | return dfs(0, 0); 49 | } 50 | 51 | public boolean checkValid(int x, int y) { 52 | return x / 10 + x % 10 + y / 10 + y % 10 <= k; 53 | } 54 | 55 | public int dfs(int x, int y) { 56 | if (x < 0 || y < 0 || x >= m || y >= n || !checkValid(x, y) || visited[x][y]) 57 | return 0; 58 | 59 | visited[x][y] = true; 60 | int res = 1; 61 | for (int d = 0; d < 4; d++) { 62 | int nx = x + dirs[d], ny = y + dirs[d + 1]; 63 | res += dfs(nx, ny); 64 | } 65 | return res; 66 | } 67 | } 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /剑指Offer/剑指 Offer 21. 调整数组顺序使奇数位于偶数前面.md: -------------------------------------------------------------------------------- 1 | ## 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面 2 | 3 | https://url.cy/3q1YC2 4 | 5 | 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。 6 | 7 | 8 | 9 | 示例: 10 | 11 | 输入:nums = [1,2,3,4] 12 | 输出:[1,3,2,4] 13 | 注:[3,1,2,4] 也是正确的答案之一。 14 | 15 | 16 | 17 | 提示: 18 | 19 | 0 <= nums.length <= 50000 20 | 0 <= nums[i] <= 10000 21 | 22 | 23 | 24 | ### 代码 25 | 26 | - 双指针指向头尾元素,左指针检测到每个偶数,就与右指针交换即可。 27 | 28 | ```java 29 | class Solution { 30 | public int[] exchange(int[] nums) { 31 | int i = 0, j = nums.length - 1; 32 | while (i < j) { 33 | if (nums[i] % 2 == 1) { 34 | i++; 35 | } else { 36 | int temp = nums[i]; 37 | nums[i] = nums[j]; 38 | nums[j] = temp; 39 | j--; 40 | } 41 | } 42 | return nums; 43 | } 44 | } 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /每日一题/1009. Complement of Base 10 Integer.md: -------------------------------------------------------------------------------- 1 | ## 1009. Complement of Base 10 Integer 2 | 3 | https://leetcode.com/problems/complement-of-base-10-integer/ 4 | 5 | Every non-negative integer `N` has a binary representation. For example, `5` can be represented as `"101"` in binary, `11` as `"1011"` in binary, and so on. Note that except for `N = 0`, there are no leading zeroes in any binary representation. 6 | 7 | The *complement* of a binary representation is the number in binary you get when changing every `1` to a `0` and `0` to a `1`. For example, the complement of `"101"` in binary is `"010"` in binary. 8 | 9 | For a given number `N` in base-10, return the complement of it's binary representation as a base-10 integer. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 5 15 | Output: 2 16 | Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: 7 23 | Output: 0 24 | Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: 10 31 | Output: 5 32 | Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. 33 | ``` 34 | 35 | ### 代码 36 | 37 | ```python 38 | class Solution: 39 | def bitwiseComplement(self, N: int) -> int: 40 | 41 | X = 1 42 | while N > X: 43 | X = X * 2 + 1 44 | return X - N 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /每日一题/1010. Pairs of Songs With Total Durations Divisible by 60.md: -------------------------------------------------------------------------------- 1 | ## 1010. Pairs of Songs With Total Durations Divisible by 60 2 | 3 | https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ 4 | 5 | You are given a list of songs where the ith song has a duration of `time[i]` seconds. 6 | 7 | Return *the number of pairs of songs for which their total duration in seconds is divisible by* `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: time = [30,20,150,100,40] 15 | Output: 3 16 | Explanation: Three pairs have a total duration divisible by 60: 17 | (time[0] = 30, time[2] = 150): total duration 180 18 | (time[1] = 20, time[3] = 100): total duration 120 19 | (time[1] = 20, time[4] = 40): total duration 60 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: time = [60,60,60] 26 | Output: 3 27 | Explanation: All three pairs have a total duration of 120, which is divisible by 60. 28 | ``` 29 | 30 | 31 | 32 | **Constraints:** 33 | 34 | - `1 <= time.length <= 6 * 104` 35 | - `1 <= time[i] <= 500` 36 | 37 | ### 代码 38 | 39 | ```java 40 | class Solution { 41 | public int numPairsDivisibleBy60(int[] time) { 42 | int remainders[] = new int[60]; 43 | int count = 0; 44 | for (int t: time) { 45 | if (t % 60 == 0) { // check if a%60==0 && b%60==0 46 | count += remainders[0]; 47 | } else { // check if a%60+b%60==60 48 | count += remainders[60 - t % 60]; 49 | } 50 | remainders[t % 60]++; // remember to update the remainders 51 | } 52 | return count; 53 | } 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /每日一题/1015. Smallest Integer Divisible by K.md: -------------------------------------------------------------------------------- 1 | ## 1015. Smallest Integer Divisible by K 2 | 3 | https://leetcode.com/problems/smallest-integer-divisible-by-k/ 4 | 5 | Given a positive integer `K`, you need to find the **length** of the **smallest** positive integer `N` such that `N` is divisible by `K`, and `N` only contains the digit `1`. 6 | 7 | Return *the **length** of* `N`. If there is no such `N`, return -1. 8 | 9 | **Note:** `N` may not fit in a 64-bit signed integer. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: K = 1 17 | Output: 1 18 | Explanation: The smallest answer is N = 1, which has length 1. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: K = 2 25 | Output: -1 26 | Explanation: There is no such positive integer N divisible by 2. 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: K = 3 33 | Output: 3 34 | Explanation: The smallest answer is N = 111, which has length 3. 35 | ``` 36 | 37 | 38 | 39 | **Constraints:** 40 | 41 | - `1 <= K <= 105` 42 | 43 | ### 思路 44 | 45 | - Straight forward: using modulo, try {1, 11, 111, 1111...} % K, check if it's divisible. 46 | 47 | ### 代码 48 | 49 | ```python 50 | class Solution(object): 51 | def smallestRepunitDivByK(self, K): 52 | temp = 0 53 | for i in range(1, K+1): 54 | temp = (temp * 10 + 1) % K 55 | if temp == 0: 56 | return i 57 | return -1 58 | ``` 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /每日一题/1094. Car Pooling.md: -------------------------------------------------------------------------------- 1 | ## 1094. Car Pooling 2 | 3 | https://leetcode.com/problems/car-pooling/ 4 | 5 | You are driving a vehicle that has `capacity` empty seats initially available for passengers. The vehicle **only** drives east (ie. it **cannot** turn around and drive west.) 6 | 7 | Given a list of `trips`, `trip[i] = [num_passengers, start_location, end_location]` contains information about the `i`-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location. 8 | 9 | Return `true` if and only if it is possible to pick up and drop off all passengers for all the given trips. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: trips = [[2,1,5],[3,3,7]], capacity = 4 17 | Output: false 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: trips = [[2,1,5],[3,3,7]], capacity = 5 24 | Output: true 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: trips = [[2,1,5],[3,5,7]], capacity = 3 31 | Output: true 32 | ``` 33 | 34 | **Example 4:** 35 | 36 | ``` 37 | Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11 38 | Output: true 39 | ``` 40 | 41 | ### 代码 42 | 43 | ```python 44 | class Solution: 45 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool: 46 | loc = [0] * 1001 47 | for trip in trips: 48 | people, start_loc, end_loc = trip[0], trip[1], trip[2] 49 | loc[trip[1]] -= people 50 | loc[trip[2]] += people 51 | 52 | 53 | for c in loc: 54 | if (capacity + c) < 0: 55 | return False 56 | capacity += c 57 | return True 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /每日一题/110. Balanced Binary Tree.md: -------------------------------------------------------------------------------- 1 | ## 110. Balanced Binary Tree 2 | 3 | https://leetcode.com/problems/balanced-binary-tree/ 4 | 5 | Given a binary tree, determine if it is height-balanced. 6 | 7 | For this problem, a height-balanced binary tree is defined as: 8 | 9 | > a binary tree in which the left and right subtrees of *every* node differ in height by no more than 1. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ![img](https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg) 16 | 17 | ``` 18 | Input: root = [3,9,20,null,null,15,7] 19 | Output: true 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ![img](https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg) 25 | 26 | ``` 27 | Input: root = [1,2,2,3,3,null,null,4,4] 28 | Output: false 29 | ``` 30 | 31 | **Example 3:** 32 | 33 | ``` 34 | Input: root = [] 35 | Output: true 36 | ``` 37 | 38 | 39 | 40 | **Constraints:** 41 | 42 | - The number of nodes in the tree is in the range `[0, 5000]`. 43 | - `-104 <= Node.val <= 104` 44 | 45 | 46 | 47 | ### 代码 48 | 49 | ```java 50 | class Solution { 51 | private int height(TreeNode root) { 52 | // An empty tree has height -1 53 | if (root == null) { 54 | return -1; 55 | } 56 | return 1 + Math.max(height(root.left), height(root.right)); 57 | } 58 | 59 | public boolean isBalanced(TreeNode root) { 60 | if (root == null) 61 | return true; 62 | if (Math.abs(height(root.left) - height(root.right)) > 1) 63 | return false; 64 | else 65 | return isBalanced(root.left) && isBalanced(root.right); 66 | } 67 | } 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /每日一题/1103. Distribute Candies to People.md: -------------------------------------------------------------------------------- 1 | ## 1103. Distribute Candies to People 2 | 3 | https://leetcode.com/problems/distribute-candies-to-people/ 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: candies = 7, num_people = 4 9 | Output: [1,2,3,1] 10 | Explanation: 11 | On the first turn, ans[0] += 1, and the array is [1,0,0,0]. 12 | On the second turn, ans[1] += 2, and the array is [1,2,0,0]. 13 | On the third turn, ans[2] += 3, and the array is [1,2,3,0]. 14 | On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: candies = 10, num_people = 3 21 | Output: [5,2,3] 22 | Explanation: 23 | On the first turn, ans[0] += 1, and the array is [1,0,0]. 24 | On the second turn, ans[1] += 2, and the array is [1,2,0]. 25 | On the third turn, ans[2] += 3, and the array is [1,2,3]. 26 | On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. 27 | ``` 28 | 29 | 把糖按照1,2,3,...,n分给每个人,第一轮从1,2,3,...,n分下去,每个人都拿到糖之后,再从第一个人开始第二轮分糖,即n+1,n+2,n+3...,2n。 30 | 31 | ### 思路 32 | 33 | - while 循环,对 res 下标取余即可,直到 candies 不够分配为止 34 | - 最后检查还有没有多余的糖,有的话全部分给最后一个人。 35 | 36 | ### 代码 37 | 38 | ```python 39 | class Solution: 40 | def distributeCandies(self, candies: int, n: int) -> List[int]: 41 | res = [0] * n 42 | turn = 1 43 | while candies >= turn: 44 | res[(turn-1)%n] += turn 45 | candies -= turn 46 | turn += 1 47 | 48 | if candies > 0: 49 | # assign the remaining candies to that person 50 | res[(turn-1)%n] += candies 51 | return res 52 | 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/1165. Single-Row Keyboard.md: -------------------------------------------------------------------------------- 1 | ## 1165. Single-Row Keyboard 2 | 3 | https://leetcode.com/problems/single-row-keyboard/ 4 | 5 | There is a special keyboard with **all keys in a single row**. 6 | 7 | Given a string `keyboard` of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index `i` to index `j` is `|i - j|`. 8 | 9 | You want to type a string `word`. Write a function to calculate how much time it takes to type it with one finger. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba" 17 | Output: 4 18 | Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'. 19 | Total time = 2 + 1 + 1 = 4. 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode" 26 | Output: 73 27 | ``` 28 | 29 | 30 | 31 | **Constraints:** 32 | 33 | - `keyboard.length == 26` 34 | - `keyboard` contains each English lowercase letter exactly once in some order. 35 | - `1 <= word.length <= 10^4` 36 | - `word[i]` is an English lowercase letter. 37 | 38 | ### 代码 39 | 40 | ```java 41 | class Solution { 42 | public int calculateTime(String keyboard, String word) { 43 | Map pos = new HashMap<>(); 44 | char[] s = keyboard.toCharArray(); 45 | for (int i = 0; i < s.length; i++) 46 | pos.put(s[i], i); 47 | char[] w = word.toCharArray(); 48 | int res = 0, t = 0; 49 | for (char c : w) { 50 | res += Math.abs(pos.get(c) - t); 51 | t = pos.get(c); 52 | } 53 | return res; 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/1291. Sequential Digits.md: -------------------------------------------------------------------------------- 1 | ## 1291. Sequential Digits 2 | 3 | https://leetcode.com/problems/sequential-digits/ 4 | 5 | An integer has *sequential digits* if and only if each digit in the number is one more than the previous digit. 6 | 7 | Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: low = 100, high = 300 15 | Output: [123,234] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: low = 1000, high = 13000 22 | Output: [1234,2345,3456,4567,5678,6789,12345] 23 | ``` 24 | 25 | **Constraints:** 26 | 27 | - `10 <= low <= high <= 10^9` 28 | 29 | ### 思路 30 | 31 | - 因为 digits 有限,且 digits 一定是从“123456789”中产生,所以可以把长度为low和high之间的所有“递增数”放到一个字典中,再用二分查找找到对应的下标,最终取结果即可 32 | 33 | ### 代码 34 | 35 | ```python 36 | class Solution: 37 | def sequentialDigits(self, low: int, high: int) -> List[int]: 38 | 39 | m = len(str(low)) 40 | n = len(str(high)) 41 | 42 | s = "123456789" 43 | 44 | dic = defaultdict(list) 45 | for digit in range(m, n + 1): 46 | for i in range(len(s) - digit + 1): 47 | dic[digit].append(int(s[i:i + digit])) 48 | 49 | start, end = 0, 0 50 | start = bisect.bisect_left(dic[m], low) # 记录在字典中对应最低位的列表的下标 51 | end = bisect.bisect_right(dic[n], high) # 记录在字典中对应最高位的列表的下标 52 | 53 | res = [] 54 | if m == n: # 如果low和high的长度一样,说明结果在一个list中,取下标区间即可 55 | return dic[m][start:end] 56 | 57 | for digit in range(m, n+1): 58 | if digit == n: 59 | res += dic[digit][:end] 60 | else: 61 | res += dic[digit][start:] 62 | 63 | return res 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/1302. Deepest Leaves Sum.md: -------------------------------------------------------------------------------- 1 | ## 1302. Deepest Leaves Sum 2 | 3 | https://leetcode.com/problems/deepest-leaves-sum/ 4 | 5 | Given the `root` of a binary tree, return *the sum of values of its deepest leaves*. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ![img](https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png) 12 | 13 | ``` 14 | Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] 15 | Output: 15 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] 22 | Output: 19 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - The number of nodes in the tree is in the range `[1, 104]`. 30 | - `1 <= Node.val <= 100` 31 | 32 | 33 | 34 | ### 代码 35 | 36 | BFS 37 | 38 | ```java 39 | /** 40 | * Definition for a binary tree node. 41 | * public class TreeNode { 42 | * int val; 43 | * TreeNode left; 44 | * TreeNode right; 45 | * TreeNode() {} 46 | * TreeNode(int val) { this.val = val; } 47 | * TreeNode(int val, TreeNode left, TreeNode right) { 48 | * this.val = val; 49 | * this.left = left; 50 | * this.right = right; 51 | * } 52 | * } 53 | */ 54 | class Solution { 55 | // bfs 56 | public int deepestLeavesSum(TreeNode root) { 57 | int res = 0; 58 | Deque queue = new ArrayDeque<>(); 59 | queue.add(root); 60 | while (!queue.isEmpty()) { 61 | int size = queue.size(); 62 | int cur = 0; 63 | for (int i = 0; i < size; i++) { 64 | TreeNode node = queue.poll(); 65 | cur += node.val; 66 | if (node.left != null) queue.add(node.left); 67 | if (node.right != null) queue.add(node.right); 68 | } 69 | res = cur; 70 | } 71 | return res; 72 | } 73 | } 74 | ``` -------------------------------------------------------------------------------- /每日一题/1316. Distinct Echo Substrings.md: -------------------------------------------------------------------------------- 1 | ## 1316. Distinct Echo Substrings 2 | 3 | https://leetcode.com/problems/distinct-echo-substrings/ 4 | 5 | Return the number of **distinct** non-empty substrings of `text` that can be written as the concatenation of some string with itself (i.e. it can be written as `a + a` where `a` is some string). 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: text = "abcabcabc" 13 | Output: 3 14 | Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: text = "leetcodeleetcode" 21 | Output: 2 22 | Explanation: The 2 substrings are "ee" and "leetcodeleetcode". 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - `1 <= text.length <= 2000` 30 | - `text` has only lowercase English letters. 31 | 32 | 33 | 34 | ### 代码 35 | 36 | - 思路:字符串哈希算法。 37 | 38 | ```java 39 | class Solution { 40 | static int N = 2001, P = 131; 41 | static long[] h, p; 42 | public long query(long[] arr, int left, int right) { 43 | return arr[right] - arr[left - 1] * p[right - left + 1]; 44 | } 45 | public int distinctEchoSubstrings(String text) { 46 | int n = text.length(); 47 | char[] s = text.toCharArray(); 48 | h = new long[n + 1]; 49 | p = new long[n + 1]; 50 | p[0] = 1; 51 | Set S = new HashSet<>(); 52 | for (int i = 0; i < n; i++) { 53 | p[i + 1] = p[i] * P; 54 | h[i + 1] = h[i] * P + s[i] - '\0'; 55 | } 56 | for (int i = 0; i < n; i++) { 57 | for (int len = 2; i + len - 1 < n; len += 2) { 58 | int mid = i + len / 2; 59 | if (query(h, i + 1, mid) == query(h, mid + 1, i + len)) 60 | S.add(query(h, i + 1, mid)); 61 | } 62 | } 63 | return S.size(); 64 | } 65 | } 66 | ``` -------------------------------------------------------------------------------- /每日一题/1329. Sort the Matrix Diagonally.md: -------------------------------------------------------------------------------- 1 | ## 1329. Sort the Matrix Diagonally 2 | 3 | https://leetcode.com/problems/sort-the-matrix-diagonally/ 4 | 5 | A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`. 6 | 7 | Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return *the resulting matrix*. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ![img](https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png) 14 | 15 | ``` 16 | Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] 17 | Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] 18 | ``` 19 | 20 | 21 | 22 | **Constraints:** 23 | 24 | - `m == mat.length` 25 | - `n == mat[i].length` 26 | - `1 <= m, n <= 100` 27 | - `1 <= mat[i][j] <= 100` 28 | 29 | 30 | 31 | ### 代码 32 | 33 | - 把一条对角线上的所有数字存到一个map中,然后排序。 34 | 35 | ```python 36 | class Solution: 37 | def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: 38 | n, m = len(mat), len(mat[0]) 39 | f = defaultdict(list) 40 | for i in range(n): 41 | for j in range(m): 42 | if i - j in f: 43 | f[i - j].append(mat[i][j]) 44 | else: 45 | f[i - j] = [mat[i][j]] 46 | 47 | for k in f.keys(): 48 | f[k].sort() 49 | 50 | for i in range(n): 51 | for j in range(m): 52 | mat[i][j] = f[i - j].pop(0) # 从小到大依次pop 53 | 54 | return mat 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /每日一题/135. Candy(hard).md: -------------------------------------------------------------------------------- 1 | ## 135. Candy (hard) 2 | 3 | https://leetcode.com/problems/candy/ 4 | 5 | There are *N* children standing in a line. Each child is assigned a rating value. 6 | 7 | You are giving candies to these children subjected to the following requirements: 8 | 9 | - Each child must have at least one candy. 10 | - Children with a higher rating get more candies than their neighbors. 11 | 12 | What is the minimum candies you must give? 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: [1,0,2] 18 | Output: 5 19 | Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: [1,2,2] 26 | Output: 4 27 | Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. 28 | The third child gets 1 candy because it satisfies the above two conditions. 29 | ``` 30 | 31 | ### 代码 32 | 33 | ```java 34 | class Solution { 35 | public int candy(int[] ratings) { 36 | if (ratings == null && ratings.length == 0) 37 | return 0; 38 | 39 | int n = ratings.length; 40 | int[] candies = new int[n]; 41 | Arrays.fill(candies, 1); 42 | for (int i = 1; i < n; i++) { 43 | if (ratings[i] > ratings[i - 1]) { 44 | candies[i] = candies[i - 1] + 1; 45 | } 46 | } 47 | 48 | // sum up all the candies 49 | int sum = candies[n - 1]; 50 | for (int i = n - 2; i >= 0; i--) { 51 | if (ratings[i] > ratings[i + 1]) { 52 | candies[i] = Math.max(candies[i], candies[i + 1] + 1); 53 | } 54 | sum += candies[i]; 55 | } 56 | return sum; 57 | } 58 | } 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /每日一题/139. Word Break.md: -------------------------------------------------------------------------------- 1 | # 139. Word Break 2 | 3 | https://leetcode.com/problems/word-break/ 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: s = "leetcode", wordDict = ["leet", "code"] 9 | Output: true 10 | Explanation: Return true because "leetcode" can be segmented as "leet code". 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 17 | Output: true 18 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 19 | Note that you are allowed to reuse a dictionary word. 20 | ``` 21 | 22 | **Example 3:** 23 | 24 | ``` 25 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 26 | Output: false 27 | ``` 28 | 29 | ### 代码 30 | 31 | - DP, dp[i] means s[:i+1] can be segmented into words in the wordDicts 32 | 33 | ```python 34 | class Solution: 35 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 36 | dp = [False for _ in range(len(s) + 1)] 37 | # dp[i] means s[:i+1] can be segmented into words in the wordDicts 38 | dp[0] = True 39 | 40 | for i in range(len(s)): 41 | for j in range(i, len(s)): 42 | if dp[i] and s[i:j+1] in wordDict: 43 | dp[j+1] = True 44 | 45 | return dp[-1] 46 | ``` -------------------------------------------------------------------------------- /每日一题/1437. Check If All 1's Are at Least Length K Places Away.md: -------------------------------------------------------------------------------- 1 | ## 1437. Check If All 1's Are at Least Length K Places Away 2 | 3 | https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ 4 | 5 | Given an array `nums` of 0s and 1s and an integer `k`, return `True` if all 1's are at least `k` places away from each other, otherwise return `False`. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | **![img](https://assets.leetcode.com/uploads/2020/04/15/sample_1_1791.png)** 12 | 13 | ``` 14 | Input: nums = [1,0,0,0,1,0,0,1], k = 2 15 | Output: true 16 | Explanation: Each of the 1s are at least 2 places away from each other. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | **![img](https://assets.leetcode.com/uploads/2020/04/15/sample_2_1791.png)** 22 | 23 | ``` 24 | Input: nums = [1,0,0,1,0,1], k = 2 25 | Output: false 26 | Explanation: The second 1 and third 1 are only one apart from each other. 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: nums = [1,1,1,1,1], k = 0 33 | Output: true 34 | ``` 35 | 36 | **Example 4:** 37 | 38 | ``` 39 | Input: nums = [0,1,0,1], k = 1 40 | Output: true 41 | ``` 42 | 43 | 44 | 45 | **Constraints:** 46 | 47 | - `1 <= nums.length <= 105` 48 | - `0 <= k <= nums.length` 49 | - `nums[i]` is `0` or `1` 50 | 51 | 52 | 53 | ### 代码 54 | 55 | ```python 56 | class Solution: 57 | def kLengthApart(self, nums: List[int], k: int) -> bool: 58 | cnt = k 59 | for x in nums: 60 | if x == 1: 61 | if cnt < k: 62 | return False 63 | cnt = 0 64 | else: 65 | cnt += 1 66 | 67 | return True 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /每日一题/1446. Consecutive Characters.md: -------------------------------------------------------------------------------- 1 | ## 1446. Consecutive Characters 2 | 3 | https://leetcode.com/problems/consecutive-characters/ 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: s = "leetcode" 9 | Output: 2 10 | Explanation: The substring "ee" is of length 2 with the character 'e' only. 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: s = "abbcccddddeeeeedcba" 17 | Output: 5 18 | Explanation: The substring "eeeee" is of length 5 with the character 'e' only. 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: s = "triplepillooooow" 25 | Output: 5 26 | ``` 27 | 28 | **Example 4:** 29 | 30 | ``` 31 | Input: s = "hooraaaaaaaaaaay" 32 | Output: 11 33 | ``` 34 | 35 | **Example 5:** 36 | 37 | ``` 38 | Input: s = "tourist" 39 | Output: 1 40 | ``` 41 | 42 | ### 代码 43 | 44 | ```python 45 | def maxPower(self, s: str) -> int: 46 | res = 1 47 | count = 1 48 | cur = s[0] 49 | for i, ch in enumerate(s): 50 | if i == 0: 51 | continue 52 | if ch == cur: 53 | count += 1 54 | res = max(res, count) 55 | else: 56 | count, cur = 1, ch 57 | return res 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /每日一题/147. Insertion Sort List.md: -------------------------------------------------------------------------------- 1 | ## 147. Insertion Sort List 2 | 3 | https://leetcode.com/problems/insertion-sort-list/ 4 | 5 | Sort a linked list using insertion sort. 6 | 7 | 8 | 9 | ![img](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) 10 | A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. 11 | With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list 12 | 13 | 14 | 15 | **Algorithm of Insertion Sort:** 16 | 17 | 1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. 18 | 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. 19 | 3. It repeats until no input elements remain. 20 | 21 | 22 | **Example 1:** 23 | 24 | ``` 25 | Input: 4->2->1->3 26 | Output: 1->2->3->4 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: -1->5->3->4->0 33 | Output: -1->0->3->4->5 34 | ``` 35 | 36 | ### 代码 37 | 38 | ```java 39 | class Solution { 40 | public ListNode insertionSortList(ListNode head) { 41 | if (head == null) 42 | return null; 43 | 44 | ListNode dummy = new ListNode(0); 45 | ListNode cur = head; 46 | ListNode prev = dummy; 47 | ListNode next = null; 48 | while (cur != null) { 49 | next = cur.next; 50 | while (prev.next != null && prev.next.val < cur.val) { 51 | prev = prev.next; 52 | } 53 | cur.next = prev.next; 54 | prev.next = cur; 55 | cur = next; 56 | prev = dummy; 57 | } 58 | return dummy.next; 59 | } 60 | } 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/1481. Least Number of Unique Integers after K Removals.md: -------------------------------------------------------------------------------- 1 | ## 1481. Least Number of Unique Integers after K Removals 2 | 3 | https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/ 4 | 5 | Given an array of integers `arr` and an integer `k`. Find the *least number of unique integers* after removing **exactly** `k` elements. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: arr = [5,5,4], k = 1 11 | Output: 1 12 | Explanation: Remove the single 4, only 5 is left. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: arr = [4,3,1,1,3,3,2], k = 3 19 | Output: 2 20 | Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left. 21 | ``` 22 | 23 | 24 | 25 | **Constraints:** 26 | 27 | - `1 <= arr.length <= 10^5` 28 | - `1 <= arr[i] <= 10^9` 29 | - `0 <= k <= arr.length` 30 | 31 | ### 代码 32 | 33 | - 贪心。HashMap, sort by element's frequency 34 | 35 | ```python 36 | class Solution: 37 | def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: 38 | f = defaultdict(int) 39 | for x in arr: 40 | f[x] += 1 41 | 42 | f_size = len(f) 43 | for x in sorted(f, key = lambda x:f[x]): 44 | if k < f[x] or k == 0: 45 | return f_size 46 | 47 | k -= f[x] 48 | f_size -= 1 49 | 50 | return f_size 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /每日一题/1524. Number of Sub-arrays With Odd Sum.md: -------------------------------------------------------------------------------- 1 | # 1524. Number of Sub-arrays With Odd Sum 2 | 3 | https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/ 4 | 5 | Given an array of integers `arr`. Return *the number of sub-arrays* with **odd** sum. 6 | 7 | As the answer may grow large, the answer **must be** computed modulo `10^9 + 7`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: arr = [1,3,5] 15 | Output: 4 16 | Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]] 17 | All sub-arrays sum are [1,4,9,3,8,5]. 18 | Odd sums are [1,9,3,5] so the answer is 4. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: arr = [2,4,6] 25 | Output: 0 26 | Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]] 27 | All sub-arrays sum are [2,6,12,4,10,6]. 28 | All sub-arrays have even sum and the answer is 0. 29 | ``` 30 | 31 | **Example 3:** 32 | 33 | ``` 34 | Input: arr = [1,2,3,4,5,6,7] 35 | Output: 16 36 | ``` 37 | 38 | **Example 4:** 39 | 40 | ``` 41 | Input: arr = [100,100,99,99] 42 | Output: 4 43 | ``` 44 | 45 | **Example 5:** 46 | 47 | ``` 48 | Input: arr = [7] 49 | Output: 1 50 | ``` 51 | 52 | 53 | 54 | **Constraints:** 55 | 56 | - `1 <= arr.length <= 10^5` 57 | - `1 <= arr[i] <= 100` 58 | 59 | 60 | 61 | ## 代码 62 | 63 | - 动态规划 64 | 65 | ```python 66 | class Solution: 67 | def numOfSubarrays(self, arr: List[int]) -> int: 68 | dp = [0] * len(arr) 69 | dp[0] = arr[0] & 1 70 | 71 | for i in range(1, len(arr)): 72 | if arr[i] & 1 == 1: 73 | dp[i] = i - dp[i - 1] + 1 74 | else: 75 | dp[i] = dp[i - 1] 76 | 77 | return sum(dp) % (10**9 + 7) 78 | ``` 79 | 80 | -------------------------------------------------------------------------------- /每日一题/155. Min Stack.md: -------------------------------------------------------------------------------- 1 | ## 155. Min Stack 2 | 3 | https://leetcode.com/problems/min-stack/ 4 | 5 | 设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。 6 | 7 | - push(x)–将元素x插入栈中 8 | - pop()–移除栈顶元素 9 | - top()–得到栈顶元素 10 | - getMin()–得到栈中最小元素 11 | 12 | #### 样例 13 | 14 | ``` 15 | MinStack minStack = new MinStack(); 16 | minStack.push(-1); 17 | minStack.push(3); 18 | minStack.push(-4); 19 | minStack.getMin(); --> Returns -4. 20 | minStack.pop(); 21 | minStack.top(); --> Returns 3. 22 | minStack.getMin(); --> Returns -1. 23 | ``` 24 | 25 | ### 代码 26 | 27 | - 分别定义两个list,`mstack`存放当前遍历过的数值中的最小值,另一个`stack`作为真实的**栈**。 28 | - 原理:每次push一个数,`mstack`会先比较`min(cur, mstack.top()) `,保证顶部一定是全局最小,这样就能O(1)时间pop最小值。而`stack`则直接push到栈顶。 29 | 30 | ```java 31 | class MinStack { 32 | 33 | /** initialize your data structure here. */ 34 | public Deque stack, mstack; 35 | public MinStack() { 36 | this.stack = new ArrayDeque<>(); 37 | this.mstack = new ArrayDeque<>(); 38 | } 39 | 40 | public void push(int x) { 41 | if (mstack.isEmpty()) mstack.push(x); 42 | else mstack.push(Math.min(mstack.peek(), x)); 43 | stack.push(x); 44 | return; 45 | } 46 | 47 | public void pop() { 48 | mstack.pop(); 49 | stack.pop(); 50 | return; 51 | } 52 | 53 | public int top() { 54 | return stack.peek(); 55 | } 56 | 57 | public int getMin() { 58 | return mstack.peek(); 59 | } 60 | } 61 | 62 | /** 63 | * Your MinStack object will be instantiated and called as such: 64 | * MinStack obj = new MinStack(); 65 | * obj.push(x); 66 | * obj.pop(); 67 | * int param_3 = obj.top(); 68 | * int param_4 = obj.getMin(); 69 | */ 70 | ``` 71 | 72 | -------------------------------------------------------------------------------- /每日一题/1551. Minimum Operations to Make Array Equal.md: -------------------------------------------------------------------------------- 1 | ## 1551. Minimum Operations to Make Array Equal 2 | 3 | https://leetcode.com/problems/minimum-operations-to-make-array-equal/submissions/ 4 | 5 | You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e. `0 <= i < n`). 6 | 7 | In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e. perform `arr[x] -=1 `and `arr[y] += 1`). The goal is to make all the elements of the array **equal**. It is **guaranteed** that all the elements of the array can be made equal using some operations. 8 | 9 | Given an integer `n`, the length of the array. Return *the minimum number of operations* needed to make all the elements of arr equal. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: n = 3 17 | Output: 2 18 | Explanation: arr = [1, 3, 5] 19 | First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4] 20 | In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]. 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: n = 6 27 | Output: 9 28 | ``` 29 | 30 | 31 | 32 | **Constraints:** 33 | 34 | - `1 <= n <= 10^4` 35 | 36 | ### 代码 37 | 38 | ```java 39 | class Solution { 40 | public int minOperations(int n) { 41 | // f(x) = 2n - 1; 42 | int res = 0, start = 0; 43 | start = n / 2; 44 | 45 | int v = 2 * start + 1; 46 | for (int k = v; k <= 2 * (n - 1) + 1; k += 2) { 47 | res += k - n; 48 | } 49 | return res; 50 | } 51 | } 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /每日一题/1636. Sort Array by Increasing Frequency (easy).md: -------------------------------------------------------------------------------- 1 | ## 1636. Sort Array by Increasing Frequency (easy) 2 | 3 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order. 4 | 5 | Return the *sorted array*. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: nums = [1,1,2,2,2,3] 13 | Output: [3,1,1,2,2,2] 14 | Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: nums = [2,3,1,3,2] 21 | Output: [1,3,3,2,2] 22 | Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: nums = [-1,1,-6,4,5,-6,1,4,1] 29 | Output: [5,-1,4,4,-6,-6,1,1,1] 30 | ``` 31 | 32 | ### 代码 33 | 34 | ```python 35 | def frequencySort(self, nums: List[int]) -> List[int]: 36 | cnt = collections.Counter(nums) 37 | return sorted(nums, key = lambda n: (cnt[n], -n)) 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /每日一题/1641. Count Sorted Vowel Strings.md: -------------------------------------------------------------------------------- 1 | ## 1641. Count Sorted Vowel Strings 2 | 3 | https://leetcode.com/problems/count-sorted-vowel-strings/ 4 | 5 | Given an integer `n`, return *the number of strings of length* `n` *that consist only of vowels (*`a`*,* `e`*,* `i`*,* `o`*,* `u`*) and are **lexicographically sorted**.* 6 | 7 | A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: n = 1 13 | Output: 5 14 | Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: n = 2 21 | Output: 15 22 | Explanation: The 15 sorted strings that consist of vowels only are 23 | ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. 24 | Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: n = 33 31 | Output: 66045 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - `1 <= n <= 50` 37 | 38 | ### 代码 39 | 40 | ```cpp 41 | class Solution { 42 | public: 43 | int countVowelStrings(int n) { 44 | int prefix[5] = {1, 2, 3, 4, 5}; 45 | while (--n) 46 | { 47 | for (int i = 1; i < 5; i++) 48 | prefix[i] += prefix[i - 1]; 49 | } 50 | return prefix[4]; 51 | } 52 | }; 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/1646. Get Maximum in Generated Array.md: -------------------------------------------------------------------------------- 1 | ## 1646. Get Maximum in Generated Array 2 | 3 | https://leetcode.com/problems/get-maximum-in-generated-array/ 4 | 5 | You are given an integer `n`. An array `nums` of length `n + 1` is generated in the following way: 6 | 7 | - `nums[0] = 0` 8 | - `nums[1] = 1` 9 | - `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` 10 | - `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` 11 | 12 | Return *the **maximum** integer in the array* `nums`. 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: n = 7 18 | Output: 3 19 | Explanation: According to the given rules: 20 | nums[0] = 0 21 | nums[1] = 1 22 | nums[(1 * 2) = 2] = nums[1] = 1 23 | nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 24 | nums[(2 * 2) = 4] = nums[2] = 1 25 | nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 26 | nums[(3 * 2) = 6] = nums[3] = 2 27 | nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 28 | Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3. 29 | ``` 30 | 31 | ### 代码 32 | 33 | - `arr[i] = arr[i / 2]` if `i` is even. 34 | - `arr[i] = arr[i / 2] + arr[i / 2 + 1]` if `i` is odd. 35 | 36 | ```java 37 | class Solution { 38 | public int getMaximumGenerated(int n) { 39 | int[] arr = new int[n + 1]; 40 | if (n == 0) return 0; 41 | if (n == 1) return 1; 42 | 43 | arr[0] = 0; 44 | arr[1] = 1; 45 | int max = 1; 46 | for (int i = 2; i <= n; i++) { 47 | if ((i & 1) == 0) 48 | arr[i] = arr[i / 2]; 49 | else 50 | arr[i] = arr[i / 2] + arr[i / 2 + 1]; 51 | 52 | if (arr[i] > max) 53 | max = arr[i]; 54 | } 55 | return max; 56 | } 57 | } 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /每日一题/1679. Max Number of K-Sum Pairs.md: -------------------------------------------------------------------------------- 1 | ## 1679. Max Number of K-Sum Pairs 2 | 3 | https://leetcode.com/problems/max-number-of-k-sum-pairs/ 4 | 5 | You are given an integer array `nums` and an integer `k`. 6 | 7 | In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. 8 | 9 | Return *the maximum number of operations you can perform on the array*. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [1,2,3,4], k = 5 17 | Output: 2 18 | Explanation: Starting with nums = [1,2,3,4]: 19 | - Remove numbers 1 and 4, then nums = [2,3] 20 | - Remove numbers 2 and 3, then nums = [] 21 | There are no more pairs that sum up to 5, hence a total of 2 operations. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: nums = [3,1,3,4,3], k = 6 28 | Output: 1 29 | Explanation: Starting with nums = [3,1,3,4,3]: 30 | - Remove the first two 3's, then nums = [1,4,3] 31 | There are no more pairs that sum up to 6, hence a total of 1 operation. 32 | ``` 33 | 34 | 35 | 36 | **Constraints:** 37 | 38 | - `1 <= nums.length <= 10**5` 39 | - `1 <= nums[i] <= 10**9` 40 | - `1 <= k <= 10**9` 41 | 42 | ### 代码 43 | 44 | - HashMap / dictionary 45 | 46 | ```python 47 | class Solution: 48 | def maxOperations(self, nums: List[int], k: int) -> int: 49 | f = defaultdict(int) 50 | for x in nums: 51 | f[x] += 1 52 | 53 | ans = 0 54 | for x in nums: 55 | if k - x not in f: 56 | continue 57 | if f[x] == 0 or f[k - x] == 0: 58 | continue 59 | elif x == k - x and f[x] == 1: 60 | continue 61 | else: 62 | f[x] -= 1 63 | f[k - x] -= 1 64 | ans += 1 65 | return ans 66 | ``` -------------------------------------------------------------------------------- /每日一题/168. Excel Sheet Column Title.md: -------------------------------------------------------------------------------- 1 | # 168. Excel Sheet Column Title 2 | 3 | https://leetcode.com/problems/excel-sheet-column-title/ 4 | 5 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 6 | 7 | For example: 8 | 9 | ``` 10 | 1 -> A 11 | 2 -> B 12 | 3 -> C 13 | ... 14 | 26 -> Z 15 | 27 -> AA 16 | 28 -> AB 17 | ... 18 | ``` 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: 1 24 | Output: "A" 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: 28 31 | Output: "AB" 32 | ``` 33 | 34 | **Example 3:** 35 | 36 | ``` 37 | Input: 701 38 | Output: "ZY" 39 | ``` 40 | 41 | ### 代码 42 | 43 | ```python 44 | class Solution: 45 | def convertToTitle(self, n: int) -> str: 46 | A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 47 | 48 | res = "" 49 | while n > 0: 50 | res += A[(n-1) % 26] 51 | n = (n-1) // 26 52 | return res[::-1] 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/1721. Swapping Nodes in a Linked List.md: -------------------------------------------------------------------------------- 1 | ## 1721. Swapping Nodes in a Linked List 2 | 3 | https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 4 | 5 | You are given the `head` of a linked list, and an integer `k`. 6 | 7 | Return *the head of the linked list after **swapping** the values of the* `kth` *node from the beginning and the* `kth` *node from the end (the list is **1-indexed**).* 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ![img](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg) 14 | 15 | ``` 16 | Input: head = [1,2,3,4,5], k = 2 17 | Output: [1,4,3,2,5] 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 24 | Output: [7,9,6,6,8,7,3,0,9,5] 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: head = [1], k = 1 31 | Output: [1] 32 | ``` 33 | 34 | **Example 4:** 35 | 36 | ``` 37 | Input: head = [1,2], k = 1 38 | Output: [2,1] 39 | ``` 40 | 41 | **Example 5:** 42 | 43 | ``` 44 | Input: head = [1,2,3], k = 2 45 | Output: [1,2,3] 46 | ``` 47 | 48 | 49 | 50 | **Constraints:** 51 | 52 | - The number of nodes in the list is `n`. 53 | - `1 <= k <= n <= 105` 54 | - `0 <= Node.val <= 100` 55 | 56 | ### 代码 57 | 58 | ```python 59 | class Solution(object): 60 | def swapNodes(self, head, k): 61 | """ 62 | :type head: ListNode 63 | :type k: int 64 | :rtype: ListNode 65 | """ 66 | dummy = ListNode(-1) 67 | dummy.next = head 68 | p = dummy 69 | i = 0 70 | while i < k: # 第k个 71 | p = p.next 72 | i += 1 73 | 74 | p1 = p 75 | q = dummy 76 | while p1: # 倒数第k个 77 | p1 = p1.next 78 | q = q.next 79 | 80 | p.val, q.val = q.val, p.val 81 | return dummy.next 82 | ``` 83 | 84 | -------------------------------------------------------------------------------- /每日一题/1725. Number Of Rectangles That Can Form The Largest Square.md: -------------------------------------------------------------------------------- 1 | ## 1725. Number Of Rectangles That Can Form The Largest Square 2 | 3 | https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/ 4 | 5 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. 6 | 7 | You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. 8 | 9 | Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. 10 | 11 | Return *the **number** of rectangles that can make a square with a side length of* `maxLen`. 12 | 13 | 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: rectangles = [[5,8],[3,9],[5,12],[16,5]] 19 | Output: 3 20 | Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. 21 | The largest possible square is of length 5, and you can get it out of 3 rectangles. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: rectangles = [[2,3],[3,7],[4,3],[3,7]] 28 | Output: 3 29 | ``` 30 | 31 | 32 | 33 | **Constraints:** 34 | 35 | - `1 <= rectangles.length <= 1000` 36 | - `rectangles[i].length == 2` 37 | - `1 <= li, wi <= 109` 38 | - `li != wi` 39 | 40 | ### 代码 41 | 42 | ```python 43 | class Solution: 44 | def countGoodRectangles(self, rec: List[List[int]]) -> int: 45 | maxLen, cnt = 0, 0 46 | for r in rec: 47 | minv = min(r[0], r[1]) 48 | if minv > maxLen: 49 | maxLen = minv 50 | cnt = 1 51 | elif minv == maxLen: 52 | cnt += 1 53 | return cnt 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /每日一题/1745. Palindrome Partitioning IV.md: -------------------------------------------------------------------------------- 1 | ## 1745. Palindrome Partitioning IV 2 | 3 | https://leetcode.com/problems/palindrome-partitioning-iv/ 4 | 5 | Given a string `s`, return `true` *if it is possible to split the string* `s` *into three **non-empty** palindromic substrings. Otherwise, return* `false`. 6 | 7 | A string is said to be palindrome if it the same string when reversed. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: s = "abcbdd" 15 | Output: true 16 | Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: s = "bcbddxy" 23 | Output: false 24 | Explanation: s cannot be split into 3 palindromes. 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - `3 <= s.length <= 2000` 32 | - `s` consists only of lowercase English letters. 33 | 34 | ### 代码 35 | 36 | - DP+预处理 37 | 38 | ```java 39 | class Solution { 40 | public boolean checkPartitioning(String ss) { 41 | char[] s = ss.toCharArray(); 42 | int n = ss.length(); 43 | boolean[][] f = new boolean[n][n]; 44 | // f[i][j] := check if s[i..j] is palindrome 45 | for (int i = n - 1; i >= 0; i--) { 46 | for (int j = i; j < n; j++) { 47 | if (i == j) 48 | f[i][j] = true; 49 | else if (i + 1 == j) 50 | f[i][j] = s[i] == s[j]; 51 | else 52 | f[i][j] = (s[i] == s[j] && f[i+1][j-1]); 53 | } 54 | } 55 | // 用 i, j枚举,检查三段是否为回文串 56 | for (int i = 0; i < n - 2; i++) { 57 | for (int j = i + 1; j + 1 < n; j++) { 58 | if (f[0][i] && f[i+1][j] && f[j+1][n-1]) 59 | return true; 60 | } 61 | } 62 | return false; 63 | } 64 | } 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /每日一题/1758. Minimum Changes To Make Alternating Binary String.md: -------------------------------------------------------------------------------- 1 | ## 1758. Minimum Changes To Make Alternating Binary String 2 | 3 | https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ 4 | 5 | 将二进制字符串变成**交替字符串**需要操作的**最小**次数。操作为:0变成1,或者1变成0. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: s = "0100" 11 | Output: 1 12 | Explanation: If you change the last character to '1', s will be "0101", which is alternating. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: s = "10" 19 | Output: 0 20 | Explanation: s is already alternating. 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: s = "1111" 27 | Output: 2 28 | Explanation: You need two operations to reach "0101" or "1010". 29 | ``` 30 | 31 | ### 代码 32 | 33 | - 由于长度为`s.length`的交替字符串有两种,要么是"101.." / "010..",我们只需要分别计算从原字符串变成这两种交替字符串的次数,取最小值。 34 | 35 | ```java 36 | class Solution { 37 | public int minOperations(String ss) { 38 | char[] s = ss.toCharArray(); 39 | return Math.min(helper('0', s), helper('1', s)); // 分别从0和1开始 40 | } 41 | public int helper(char c, char[] s) { 42 | int res = 0; 43 | for (char x : s) { 44 | if (c != x) res++; // 跟交替串不同,需要操作加一 45 | // if (c == '1') c = '0'; 46 | // else c = '1'; 47 | c ^= 1; // 每次判断结束,0变成1,1变成0 48 | } 49 | return res; 50 | } 51 | } 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /每日一题/1762. Buildings With an Ocean View.md: -------------------------------------------------------------------------------- 1 | ## 1762. Buildings With an Ocean View 2 | 3 | https://leetcode.com/problems/buildings-with-an-ocean-view/ 4 | 5 | There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. 6 | 7 | The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height. 8 | 9 | Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: heights = [4,2,3,1] 17 | Output: [0,2,3] 18 | Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: heights = [4,3,2,1] 25 | Output: [0,1,2,3] 26 | Explanation: All the buildings have an ocean view. 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: heights = [1,3,2,4] 33 | Output: [3] 34 | Explanation: Only building 3 has an ocean view. 35 | ``` 36 | 37 | **Example 4:** 38 | 39 | ``` 40 | Input: heights = [2,2,2,2] 41 | Output: [3] 42 | Explanation: Buildings cannot see the ocean if there are buildings of the same height to its right. 43 | ``` 44 | 45 | 46 | 47 | ### 代码 48 | 49 | ```python 50 | class Solution: 51 | def findBuildings(self, h: List[int]) -> List[int]: 52 | res = [] 53 | res.append(len(h) - 1) 54 | maxHeight = h[-1] 55 | n = len(h) 56 | 57 | for i in range(n - 2, -1, -1): 58 | if h[i] > maxHeight: 59 | res.insert(0, i) 60 | maxHeight = h[i] 61 | 62 | return res 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /每日一题/179. Largest Number.md: -------------------------------------------------------------------------------- 1 | ## 179. Largest Number 2 | 3 | #### [题目](https://leetcode.com/problems/largest-number/) 4 | 5 | Given a list of non negative integers, arrange them such that they form the largest number. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [10,2] 11 | Output: "210" 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: [3,30,34,5,9] 18 | Output: "9534330" 19 | ``` 20 | 21 | #### 代码 22 | 23 | ```java 24 | class Solution { 25 | public String largestNumber(int[] nums) { 26 | if (nums == null || nums.length == 0) 27 | return ""; 28 | 29 | String[] snum = new String[nums.length]; 30 | for (int i = 0; i < nums.length; i++) { 31 | snum[i] = String.valueOf(nums[i]); 32 | } 33 | 34 | Comparator comp = new Comparator(){ 35 | @Override 36 | public int compare(String o1, String o2) { 37 | // TODO Auto-generated method stub 38 | String s1 = o1 + o2; 39 | String s2 = o2 + o1; 40 | return s2.compareTo(s1); 41 | } 42 | }; 43 | 44 | Arrays.sort(snum, comp); 45 | // if all digits are zero 46 | if (snum[0].charAt(0) == '0') 47 | return "0"; 48 | 49 | StringBuilder sb = new StringBuilder(); 50 | for (String s: snum) { 51 | sb.append(s); 52 | } 53 | return sb.toString(); 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/1822. Sign of the Product of an Array.md: -------------------------------------------------------------------------------- 1 | ## 1822. Sign of the Product of an Array 2 | 3 | https://leetcode.com/problems/sign-of-the-product-of-an-array/ 4 | 5 | There is a function `signFunc(x)` that returns: 6 | 7 | - `1` if `x` is positive. 8 | - `-1` if `x` is negative. 9 | - `0` if `x` is equal to `0`. 10 | 11 | You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. 12 | 13 | Return `signFunc(product)`. 14 | 15 | 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: nums = [-1,-2,-3,-4,3,2,1] 21 | Output: 1 22 | Explanation: The product of all values in the array is 144, and signFunc(144) = 1 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: nums = [1,5,0,2,-3] 29 | Output: 0 30 | Explanation: The product of all values in the array is 0, and signFunc(0) = 0 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: nums = [-1,1,-1,1,-1] 37 | Output: -1 38 | Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 39 | ``` 40 | 41 | 42 | 43 | **Constraints:** 44 | 45 | - `1 <= nums.length <= 1000` 46 | - `-100 <= nums[i] <= 100` 47 | 48 | 49 | 50 | ### 代码 51 | 52 | ```java 53 | class Solution { 54 | public int arraySign(int[] nums) { 55 | int pos = 0, neg = 0; 56 | for (int x : nums) { 57 | if (x < 0) neg++; 58 | else if (x > 0) pos++; 59 | else return 0; 60 | } 61 | return neg % 2 == 1 ? -1 : 1; 62 | } 63 | } 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/1827. Minimum Operations to Make the Array Increasing.md: -------------------------------------------------------------------------------- 1 | ## 1827. Minimum Operations to Make the Array Increasing 2 | 3 | https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ 4 | 5 | You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`. 6 | 7 | - For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`. 8 | 9 | Return *the **minimum** number of operations needed to make* `nums` ***strictly** **increasing**.* 10 | 11 | An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing. 12 | 13 | 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: nums = [1,1,1] 19 | Output: 3 20 | Explanation: You can do the following operations: 21 | 1) Increment nums[2], so nums becomes [1,1,2]. 22 | 2) Increment nums[1], so nums becomes [1,2,2]. 23 | 3) Increment nums[2], so nums becomes [1,2,3]. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: nums = [1,5,2,4,1] 30 | Output: 14 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: nums = [8] 37 | Output: 0 38 | ``` 39 | 40 | 41 | 42 | **Constraints:** 43 | 44 | - `1 <= nums.length <= 5000` 45 | - `1 <= nums[i] <= 10**4` 46 | 47 | 48 | 49 | ### 代码 50 | 51 | ```java 52 | class Solution { 53 | public int minOperations(int[] nums) { 54 | int res = 0, t = nums[0]; 55 | for (int i = 1; i < nums.length; i++) { 56 | if (nums[i] < t + 1) 57 | res += (t + 1 - nums[i]); 58 | t = Math.max(nums[i], t + 1); 59 | } 60 | return res; 61 | } 62 | } 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /每日一题/1832. Check if the Sentence Is Pangram.md: -------------------------------------------------------------------------------- 1 | ## 1832. Check if the Sentence Is Pangram 2 | 3 | https://leetcode.com/problems/check-if-the-sentence-is-pangram/ 4 | 5 | A **pangram** is a sentence where every letter of the English alphabet appears at least once. 6 | 7 | Given a string `sentence` containing only lowercase English letters, return `true` *if* `sentence` *is a **pangram**, or* `false` *otherwise.* 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: sentence = "thequickbrownfoxjumpsoverthelazydog" 15 | Output: true 16 | Explanation: sentence contains at least one of every letter of the English alphabet. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: sentence = "leetcode" 23 | Output: false 24 | ``` 25 | 26 | 27 | 28 | **Constraints:** 29 | 30 | - `1 <= sentence.length <= 1000` 31 | - `sentence` consists of lowercase English letters. 32 | 33 | 34 | 35 | ### 代码 36 | 37 | - HashSet 38 | 39 | ```java 40 | class Solution { 41 | public boolean checkIfPangram(String s) { 42 | Set hash = new HashSet<>(); 43 | for (char ch : s.toCharArray()) 44 | if (!hash.contains(ch)) 45 | hash.add(ch); 46 | return hash.size() == 26; 47 | } 48 | } 49 | ``` 50 | 51 | - Bitwise 52 | 53 | ```java 54 | class Solution { 55 | public boolean checkIfPangram(String sentence) { 56 | int seen = 0; 57 | for(char c : sentence.toCharArray()) { 58 | int ci = c - 'a'; 59 | seen = seen | (1 << ci); 60 | } 61 | return seen == ((1 << 26) - 1); 62 | } 63 | } 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/1837. Sum of Digits in Base K.md: -------------------------------------------------------------------------------- 1 | ## 1837. Sum of Digits in Base K 2 | 3 | https://leetcode.com/problems/sum-of-digits-in-base-k/ 4 | 5 | Given an integer `n` (in base `10`) and a base `k`, return *the **sum** of the digits of* `n` ***after** converting* `n` *from base* `10` *to base* `k`. 6 | 7 | After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: n = 34, k = 6 15 | Output: 9 16 | Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: n = 10, k = 10 23 | Output: 1 24 | Explanation: n is already in base 10. 1 + 0 = 1. 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - `1 <= n <= 100` 32 | - `2 <= k <= 10` 33 | 34 | ### 代码 35 | 36 | 简单的10进制转K进制问题 37 | 38 | ```java 39 | class Solution { 40 | public int sumBase(int n, int k) { 41 | int sum = 0; 42 | while (n > 0) { 43 | sum += n % k; 44 | n /= k; 45 | } 46 | return sum; 47 | } 48 | } 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /每日一题/1848. Minimum Distance to the Target Element.md: -------------------------------------------------------------------------------- 1 | ## 1848. Minimum Distance to the Target Element 2 | 3 | https://leetcode.com/problems/minimum-distance-to-the-target-element/ 4 | 5 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. 6 | 7 | Return `abs(i - start)`. 8 | 9 | It is **guaranteed** that `target` exists in `nums`. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [1,2,3,4,5], target = 5, start = 3 17 | Output: 1 18 | Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: nums = [1], target = 1, start = 0 25 | Output: 0 26 | Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0 33 | Output: 0 34 | Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0. 35 | ``` 36 | 37 | 38 | 39 | **Constraints:** 40 | 41 | - `1 <= nums.length <= 1000` 42 | - `1 <= nums[i] <= 104` 43 | - `0 <= start < nums.length` 44 | - `target` is in `nums`. 45 | 46 | 47 | 48 | ### 代码 49 | 50 | ```java 51 | class Solution { 52 | public int getMinDistance(int[] nums, int target, int start) { 53 | int minv = Integer.MAX_VALUE; 54 | int i = 0; 55 | for (int x : nums) { 56 | if (x == target) 57 | minv = Math.min(minv, Math.abs(i - start)); 58 | i++; 59 | } 60 | return minv; 61 | } 62 | } 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /每日一题/1854. Maximum Population Year.md: -------------------------------------------------------------------------------- 1 | ## 1854. Maximum Population Year 2 | 3 | https://leetcode.com/problems/maximum-population-year/ 4 | 5 | You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. 6 | 7 | The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die. 8 | 9 | Return *the **earliest** year with the **maximum population***. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: logs = [[1993,1999],[2000,2010]] 17 | Output: 1993 18 | Explanation: The maximum population is 1, and 1993 is the earliest year with this population. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: logs = [[1950,1961],[1960,1971],[1970,1981]] 25 | Output: 1960 26 | Explanation: 27 | The maximum population is 2, and it had happened in years 1960 and 1970. 28 | The earlier year between them is 1960. 29 | ``` 30 | 31 | 32 | 33 | **Constraints:** 34 | 35 | - `1 <= logs.length <= 100` 36 | - `1950 <= birth i < death i <= 2050` 37 | 38 | ### 代码 39 | 40 | ```java 41 | class Solution { 42 | public int maximumPopulation(int[][] logs) { 43 | int res = 0, cnt = 0; 44 | for (int i = 1950; i <= 2050; i++) { 45 | int s = 0; 46 | for (int[] log : logs) { 47 | if (i >= log[0] && i < log[1]) 48 | s++; 49 | } 50 | if (s > cnt) { 51 | res = i; 52 | cnt = s; 53 | } 54 | } 55 | return res; 56 | } 57 | } 58 | ``` 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /每日一题/187. Repeated DNA Sequences.md: -------------------------------------------------------------------------------- 1 | ## 187. Repeated DNA Sequences 2 | 3 | https://leetcode.com/problems/repeated-dna-sequences/ 4 | 5 | All DNA is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`, for example: `"ACGAATTCCG"`. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 6 | 7 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 15 | Output: ["AAAAACCCCC","CCCCCAAAAA"] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: s = "AAAAAAAAAAAAA" 22 | Output: ["AAAAAAAAAA"] 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - `0 <= s.length <= 105` 30 | - `s[i]` is `'A'`, `'C'`, `'G'`, or `'T'`. 31 | 32 | ### 代码 33 | 34 | - HashMap + HashSet 35 | 36 | ```Python 37 | # Python 38 | class Solution: 39 | def findRepeatedDnaSequences(self, s: str) -> List[str]: 40 | res = [] 41 | dic = defaultdict(int) 42 | if not s or len(s) <= 10: 43 | return [] 44 | for idx in range(len(s) - 9): 45 | dic[s[idx:idx+10]] += 1 46 | if dic[s[idx:idx+10]] > 1: 47 | res.append(s[idx:idx+10]) 48 | 49 | return list(set(res)) 50 | ``` 51 | 52 | ```Java 53 | // Java 54 | class Solution { 55 | public List findRepeatedDnaSequences(String s) { 56 | Set seen = new HashSet(), repeated = new HashSet(); 57 | for (int i = 0; i + 9 < s.length(); i++) { 58 | String ten = s.substring(i, i + 10); 59 | if (!seen.add(ten)) 60 | repeated.add(ten); 61 | } 62 | return new ArrayList(repeated); 63 | } 64 | } 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /每日一题/19. Remove Nth Node From End of List.md: -------------------------------------------------------------------------------- 1 | ## 19. Remove Nth Node From End of List 2 | 3 | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 4 | 5 | Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. 6 | 7 | **Follow up:** Could you do this in one pass? 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ![img](https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg) 14 | 15 | ``` 16 | Input: head = [1,2,3,4,5], n = 2 17 | Output: [1,2,3,5] 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: head = [1], n = 1 24 | Output: [] 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: head = [1,2], n = 1 31 | Output: [1] 32 | ``` 33 | 34 | 35 | 36 | **Constraints:** 37 | 38 | - The number of nodes in the list is `sz`. 39 | - `1 <= sz <= 30` 40 | - `0 <= Node.val <= 100` 41 | - `1 <= n <= sz` 42 | 43 | 44 | 45 | ### 代码 46 | 47 | ```java 48 | /** 49 | * Definition for singly-linked list. 50 | * public class ListNode { 51 | * int val; 52 | * ListNode next; 53 | * ListNode() {} 54 | * ListNode(int val) { this.val = val; } 55 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 56 | * } 57 | */ 58 | class Solution { 59 | public ListNode removeNthFromEnd(ListNode head, int n) { 60 | if (head == null || head.next == null) return null; 61 | int k = n; 62 | ListNode first = head, second = head; 63 | while (k-- > 0) { 64 | second = second.next; 65 | } 66 | if (second == null) 67 | return head.next; 68 | while (second != null && second.next != null) { 69 | first = first.next; 70 | second = second.next; 71 | } 72 | first.next = first.next.next; 73 | return head; 74 | } 75 | } 76 | ``` 77 | 78 | -------------------------------------------------------------------------------- /每日一题/199. Binary Tree Right Side View.md: -------------------------------------------------------------------------------- 1 | ## 199. Binary Tree Right Side View 2 | 3 | https://leetcode.com/problems/binary-tree-right-side-view/ 4 | 5 | Given 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. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: [1,2,3,null,5,null,4] 11 | Output: [1, 3, 4] 12 | Explanation: 13 | 14 | 1 <--- 15 | / \ 16 | 2 3 <--- 17 | \ \ 18 | 5 4 <--- 19 | ``` 20 | 21 | 22 | 23 | ### 代码 24 | 25 | - BFS层序遍历 26 | 27 | ```java 28 | class Solution { 29 | public List rightSideView(TreeNode root) { 30 | List res = new ArrayList<>(); 31 | Deque queue = new ArrayDeque<>(); 32 | if (root == null) 33 | return res; 34 | queue.offer(root); 35 | while (!queue.isEmpty()) { 36 | int size = queue.size(); 37 | for (int i = 0; i < size; i++) { 38 | TreeNode node = queue.poll(); 39 | if (node.left != null) 40 | queue.offer(node.left); 41 | if (node.right != null) 42 | queue.offer(node.right); 43 | if (i == size - 1) 44 | res.add(node.val); 45 | } 46 | } 47 | return res; 48 | } 49 | } 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /每日一题/20. Valid Parentheses.md: -------------------------------------------------------------------------------- 1 | ## 20. Valid Parentheses 2 | 3 | https://leetcode.com/problems/valid-parentheses/ 4 | 5 | Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | 1. Open brackets must be closed by the same type of brackets. 10 | 2. Open brackets must be closed in the correct order. 11 | 12 | 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: s = "()" 18 | Output: true 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: s = "()[]{}" 25 | Output: true 26 | ``` 27 | 28 | **Example 3:** 29 | 30 | ``` 31 | Input: s = "(]" 32 | Output: false 33 | ``` 34 | 35 | **Example 4:** 36 | 37 | ``` 38 | Input: s = "([)]" 39 | Output: false 40 | ``` 41 | 42 | **Example 5:** 43 | 44 | ``` 45 | Input: s = "{[]}" 46 | Output: true 47 | ``` 48 | 49 | 50 | 51 | **Constraints:** 52 | 53 | - `1 <= s.length <= 104` 54 | - `s` consists of parentheses only `'()[]{}'`. 55 | 56 | 57 | 58 | 59 | 60 | ### 代码 61 | 62 | ```python 63 | class Solution(object): 64 | def isValid(self, s): 65 | """ 66 | :type s: str 67 | :rtype: bool 68 | """ 69 | stk = [] 70 | for ch in s: 71 | if not stk and (ch == '}' or ch == ')' or ch == ']'): 72 | return False 73 | if ch == '(' or ch == '{' or ch == '[': 74 | stk.append(ch) 75 | continue 76 | if stk: 77 | if ch == ')' and stk[-1] == '(': 78 | stk.pop() 79 | elif ch == '}' and stk[-1] == '{': 80 | stk.pop() 81 | elif ch == ']' and stk[-1] == '[': 82 | stk.pop() 83 | else: 84 | return False 85 | return True if stk == [] else False 86 | ``` 87 | 88 | -------------------------------------------------------------------------------- /每日一题/205. Isomorphic Strings.md: -------------------------------------------------------------------------------- 1 | ## 205. Isomorphic Strings 2 | 3 | https://leetcode.com/problems/isomorphic-strings/ 4 | 5 | Given two strings `s` and `t`, *determine if they are isomorphic*. 6 | 7 | Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. 8 | 9 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: s = "egg", t = "add" 17 | Output: true 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: s = "foo", t = "bar" 24 | Output: false 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: s = "paper", t = "title" 31 | Output: true 32 | ``` 33 | 34 | 35 | 36 | **Constraints:** 37 | 38 | - `1 <= s.length <= 5 * 104` 39 | - `t.length == s.length` 40 | - `s` and `t` consist of any valid ascii character. 41 | 42 | 43 | 44 | ### 代码 45 | 46 | - 思路:分别对s和t互相建立映射关系,用数组下标表示。 47 | 48 | ```java 49 | class Solution { 50 | public boolean isIsomorphic(String _s, String _t) { 51 | char[] s = _s.toCharArray(); 52 | char[] t = _t.toCharArray(); 53 | int[] a = new int[256]; 54 | int[] b = new int[256]; 55 | Arrays.fill(a, -1); 56 | Arrays.fill(b, -1); 57 | // 映射关系 a[s[i]] -> t[i], b[t[i]] = s[i] 58 | for (int i = 0; i < s.length; i++) { 59 | int u = s[i] - '\0'; 60 | int v = t[i] - '\0'; 61 | if (a[u] == -1 && b[v] == -1) { 62 | a[u] = v; 63 | b[v] = u; 64 | continue; 65 | } 66 | else if (a[u] != v || b[v] != u) 67 | return false; 68 | } 69 | return true; 70 | } 71 | } 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /每日一题/21. Merge Two Sorted Lists.md: -------------------------------------------------------------------------------- 1 | ## 21. Merge Two Sorted Lists 2 | 3 | Merge two sorted linked lists and return it as a **sorted** list. The list should be made by splicing together the nodes of the first two lists. 4 | 5 | 6 | 7 | **Example 1:** 8 | 9 | ![img](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg) 10 | 11 | ``` 12 | Input: l1 = [1,2,4], l2 = [1,3,4] 13 | Output: [1,1,2,3,4,4] 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: l1 = [], l2 = [] 20 | Output: [] 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: l1 = [], l2 = [0] 27 | Output: [0] 28 | ``` 29 | 30 | 31 | 32 | **Constraints:** 33 | 34 | - The number of nodes in both lists is in the range `[0, 50]`. 35 | - `-100 <= Node.val <= 100` 36 | - Both `l1` and `l2` are sorted in **non-decreasing** order. 37 | 38 | ### 代码 39 | 40 | ```java 41 | class Solution { 42 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 43 | ListNode dummy = new ListNode(0); 44 | ListNode cur = dummy; 45 | while (l1 != null && l2 != null) { 46 | if (l1.val < l2.val) { 47 | cur.next = l1; 48 | l1 = l1.next; 49 | } else { 50 | cur.next = l2; 51 | l2 = l2.next; 52 | } 53 | cur = cur.next; 54 | } 55 | cur.next = (l1 == null) ? l2 : l1; 56 | return dummy.next; 57 | } 58 | } 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /每日一题/216. Combination Sum III.md: -------------------------------------------------------------------------------- 1 | ## 216. Combination Sum III 2 | 3 | https://leetcode.com/problems/combination-sum-iii/ 4 | 5 | Find all possible combinations of ***k*** numbers that add up to a number ***n***, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 6 | 7 | **Note:** 8 | 9 | - All numbers will be positive integers. 10 | - The solution set must not contain duplicate combinations. 11 | 12 | **Example 1:** 13 | 14 | ``` 15 | Input: k = 3, n = 7 16 | Output: [[1,2,4]] 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: k = 3, n = 9 23 | Output: [[1,2,6], [1,3,5], [2,3,4]] 24 | ``` 25 | 26 | ### 代码 27 | 28 | - DFS 29 | 30 | ```python 31 | ''' 32 | Input: k = 3, n = 7 33 | Output: [[1,2,4]] 34 | 35 | 36 | Input: k = 3, n = 9 37 | Output: [[1,2,6], [1,3,5], [2,3,4]] 38 | ''' 39 | class Solution(object): 40 | def combinationSum3(self, k, n): 41 | """ 42 | :type k: int 43 | :type n: int 44 | :rtype: List[List[int]] 45 | """ 46 | res = [] 47 | arr = [x for x in range(1,10)] 48 | 49 | def dfs(arr, target, index, res, digit, temp): 50 | if digit == k and target == 0: 51 | res.append(temp) 52 | return 53 | 54 | for i in range(index, len(arr)): 55 | if arr[i] in temp: 56 | continue 57 | dfs(arr, target-arr[i], i+1, res, digit+1, temp+[arr[i]]) 58 | 59 | dfs(arr, n, 0, res, 0, []) 60 | return res 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/240. Search a 2D Matrix II.md: -------------------------------------------------------------------------------- 1 | ## 240. Search a 2D Matrix II 2 | 3 | Write an efficient algorithm that searches for a `target` value in an `m x n` integer `matrix`. The `matrix` has the following properties: 4 | 5 | - Integers in each row are sorted in ascending from left to right. 6 | - Integers in each column are sorted in ascending from top to bottom. 7 | 8 | 9 | 10 | **Example 1:** 11 | 12 | ![img](https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg) 13 | 14 | ``` 15 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 16 | Output: true 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ![img](https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg) 22 | 23 | ``` 24 | Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 25 | Output: false 26 | ``` 27 | 28 | 29 | 30 | **Constraints:** 31 | 32 | - `m == matrix.length` 33 | - `n == matrix[i].length` 34 | - `1 <= n, m <= 300` 35 | - `-10**9 <= matix[i][j] <= 10**9` 36 | - All the integers in each row are **sorted** in ascending order. 37 | - All the integers in each column are **sorted** in ascending order. 38 | - `-10**9 <= target <= 10**9` 39 | 40 | ### 代码 41 | 42 | ```java 43 | class Solution { 44 | public boolean searchMatrix(int[][] matrix, int target) { 45 | int n = matrix.length, m = matrix[0].length; 46 | int i = 0, j = m - 1; 47 | while (i < n && j >= 0) { 48 | int cur = matrix[i][j]; 49 | if (cur > target) j--; 50 | else if (cur < target) i++; 51 | else return true; 52 | } 53 | return false; 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/243. Shortest Word Distance.md: -------------------------------------------------------------------------------- 1 | ## 243. Shortest Word Distance 2 | 3 | https://leetcode.com/problems/shortest-word-distance/ 4 | 5 | Given a list of words and two words *word1* and *word2*, return the shortest distance between these two words in the list. 6 | 7 | **Example:** 8 | Assume that words = `["practice", "makes", "perfect", "coding", "makes"]`. 9 | 10 | ``` 11 | Input: word1 = “coding”, word2 = “practice” 12 | Output: 3 13 | Input: word1 = "makes", word2 = "coding" 14 | Output: 1 15 | ``` 16 | 17 | **Note:** 18 | You may assume that *word1* **does not equal to** *word2*, and *word1* and *word2* are both in the list. 19 | 20 | ### 代码 21 | 22 | ```python 23 | class Solution: 24 | def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: 25 | # O(N) 26 | i1,i2=-1,-1 27 | ans=len(words) 28 | for i,w in enumerate(words): 29 | if w==word1: 30 | i1=i 31 | elif w==word2: 32 | i2=i 33 | if i1!=-1 and i2!=-1: 34 | ans=min(ans,abs(i1-i2)) 35 | return ans 36 | ``` 37 | 38 | -------------------------------------------------------------------------------- /每日一题/246. Strobogrammatic Number.md: -------------------------------------------------------------------------------- 1 | ## 246. Strobogrammatic Number 2 | 3 | https://leetcode.com/problems/strobogrammatic-number/ 4 | 5 | Given a string `num` which represents an integer, return `true` *if* `num` *is a **strobogrammatic number***. 6 | 7 | A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: num = "69" 15 | Output: true 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: num = "88" 22 | Output: true 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: num = "962" 29 | Output: false 30 | ``` 31 | 32 | **Example 4:** 33 | 34 | ``` 35 | Input: num = "1" 36 | Output: true 37 | ``` 38 | 39 | 40 | 41 | **Constraints:** 42 | 43 | - `1 <= num.length <= 50` 44 | - `num` consists of only digits. 45 | - `num` does not contain any leading zeros except for zero itself. 46 | 47 | ### 代码 48 | 49 | ```java 50 | class Solution { 51 | public boolean isStrobogrammatic(String num) { 52 | Map hash = new HashMap<>(); 53 | hash.put('1', '1'); 54 | hash.put('6', '9'); 55 | hash.put('9', '6'); 56 | hash.put('0', '0'); 57 | hash.put('8', '8'); 58 | StringBuilder temp = new StringBuilder(); 59 | for (char ch : num.toCharArray()) { 60 | if (!hash.containsKey(ch)) return false; 61 | temp.append(hash.get(ch)); 62 | } 63 | return temp.reverse().toString().equals(num); 64 | } 65 | } 66 | ``` 67 | 68 | -------------------------------------------------------------------------------- /每日一题/261. Graph Valid Tree.md: -------------------------------------------------------------------------------- 1 | ## 261. Graph Valid Tree 2 | 3 | https://leetcode.com/problems/graph-valid-tree/ 4 | 5 | Given `n` nodes labeled from `0` to `n-1` and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] 11 | Output: true 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]] 18 | Output: false 19 | ``` 20 | 21 | **Note**: you can assume that no duplicate edges will appear in `edges`. Since all edges are undirected, `[0,1]` is the same as `[1,0]` and thus will not appear together in `edges`. 22 | 23 | ### 代码 24 | 25 | ```python 26 | class Solution: 27 | def validTree(self, n: int, edges: List[List[int]]) -> bool: 28 | if len(edges) != n - 1: return False 29 | adj = [[] for _ in range(n)] 30 | for u, v in edges: 31 | adj[u].append(v) 32 | adj[v].append(u) 33 | parent = {0: -1} 34 | stack = [0] 35 | 36 | while stack: 37 | cur = stack.pop() 38 | for nb in adj[cur]: 39 | if nb == parent[cur]: 40 | continue 41 | if nb in parent: 42 | return False 43 | parent[nb] = cur 44 | stack.append(nb) 45 | 46 | return len(parent) == n 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /每日一题/285. Inorder Successor in BST.md: -------------------------------------------------------------------------------- 1 | ## 285. Inorder Successor in BST 2 | 3 | https://leetcode.com/problems/inorder-successor-in-bst/ 4 | 5 | Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 6 | 7 | The successor of a node `p` is the node with the smallest key greater than `p.val`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ![img](https://assets.leetcode.com/uploads/2019/01/23/285_example_1.PNG) 14 | 15 | ``` 16 | Input: root = [2,1,3], p = 1 17 | Output: 2 18 | Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ![img](https://assets.leetcode.com/uploads/2019/01/23/285_example_2.PNG) 24 | 25 | ``` 26 | Input: root = [5,3,6,2,4,null,null,1], p = 6 27 | Output: null 28 | Explanation: There is no in-order successor of the current node, so the answer is null. 29 | ``` 30 | 31 | 32 | 33 | **Note:** 34 | 35 | 1. If the given node has no in-order successor in the tree, return `null`. 36 | 2. It's guaranteed that the values of the tree are unique. 37 | 38 | ### 代码 39 | 40 | ```python 41 | # Definition for a binary tree node. 42 | # class TreeNode: 43 | # def __init__(self, x): 44 | # self.val = x 45 | # self.left = None 46 | # self.right = None 47 | 48 | class Solution: 49 | def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': 50 | succ = None 51 | while root: 52 | if p.val < root.val: 53 | succ = root 54 | root = root.left 55 | else: 56 | root = root.right 57 | return succ 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /每日一题/287. Find the Duplicate Numeber.md: -------------------------------------------------------------------------------- 1 | ## 287. Find the Duplicate Numeber 2 | 3 | https://leetcode.com/problems/find-the-duplicate-number/ 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: nums = [1,3,4,2,2] 9 | Output: 2 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: nums = [3,1,3,4,2] 16 | Output: 3 17 | ``` 18 | 19 | **Example 3:** 20 | 21 | ``` 22 | Input: nums = [1,1] 23 | Output: 1 24 | ``` 25 | 26 | **Example 4:** 27 | 28 | ``` 29 | Input: nums = [1,1,2] 30 | Output: 1 31 | ``` 32 | 33 | 34 | 35 | **Constraints:** 36 | 37 | - `2 <= n <= 3 * 104` 38 | - `nums.length == n + 1` 39 | - `1 <= nums[i] <= n` 40 | - All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. 41 | 42 | ### 代码 43 | 44 | - 参考LC142题,快慢指针寻找环入口,模板题 45 | 46 | ```java 47 | class Solution { 48 | public int findDuplicate(int[] nums) { 49 | int a = 0, b = 0; 50 | while (true) { 51 | a = nums[a]; // slow = slow.next 52 | b = nums[nums[b]]; // fast = fast.next.next 53 | if (a == b) { 54 | a = 0; 55 | while (a != b) { 56 | a = nums[a]; 57 | b = nums[b]; 58 | } 59 | return a; // 环的入口 60 | } 61 | } 62 | } 63 | } 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/290. Word Pattern.md: -------------------------------------------------------------------------------- 1 | ## 290. Word Pattern 2 | 3 | https://leetcode.com/problems/word-pattern/ 4 | 5 | Given a `pattern` and a string `str`, find if `str` follows the same pattern. 6 | 7 | Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `str`. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: pattern = "abba", str = "dog cat cat dog" 13 | Output: true 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input:pattern = "abba", str = "dog cat cat fish" 20 | Output: false 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: pattern = "aaaa", str = "dog cat cat dog" 27 | Output: false 28 | ``` 29 | 30 | **Example 4:** 31 | 32 | ``` 33 | Input: pattern = "abba", str = "dog dog dog dog" 34 | Output: false 35 | ``` 36 | 37 | **Notes:** 38 | You may assume `pattern` contains only lowercase letters, and `str` contains lowercase letters that may be separated by a single space. 39 | 40 | 41 | 42 | ### 代码 43 | 44 | - edge cases 比较多,比如长度要匹配,如何建立两次映射,即 pattern 到 str 和 str 到 pattern 的对应。用两个 dictionary 即可。 45 | 46 | ```python 47 | class Solution: 48 | def wordPattern(self, pattern: str, A: str) -> bool: 49 | 50 | if not pattern or not A: 51 | return False 52 | if len(pattern) != len(A.split()): 53 | return False 54 | 55 | S = A.split() # ["word1","word2","word3"] 56 | d1 = defaultdict(str) 57 | d2 = defaultdict(str) 58 | for i, ch in enumerate(pattern): 59 | if ch not in d1 and S[i] not in d2: 60 | d1[ch] = S[i] 61 | d2[S[i]] = ch 62 | 63 | elif ch not in d1 and d2[S[i]] != ch: 64 | return False 65 | 66 | elif ch in d1 and S[i] != d1[ch]: 67 | return False 68 | 69 | return True 70 | ``` 71 | 72 | -------------------------------------------------------------------------------- /每日一题/295. Find Median from Data Stream.md: -------------------------------------------------------------------------------- 1 | # 295. Find Median from Data Stream 2 | 3 | https://leetcode.com/problems/find-median-from-data-stream/ 4 | 5 | **Two Heap Classical Problem** 6 | 7 | ``` 8 | addNum(1) 9 | addNum(2) 10 | findMedian() -> 1.5 11 | addNum(3) 12 | findMedian() -> 2 13 | ``` 14 | 15 | ### Two-Heap Solution 16 | 17 | ```python 18 | class MedianFinder(object): 19 | 20 | def __init__(self): 21 | self.maxHeap = [] 22 | self.minHeap = [] 23 | 24 | def addNum(self, num): 25 | if not self.maxHeap or -self.maxHeap[0] > num: 26 | heappush(self.maxHeap, -num) 27 | else: 28 | heappush(self.minHeap, num) 29 | 30 | if len(self.maxHeap) > len(self.minHeap) + 1: 31 | heappush(self.minHeap, -heappop(self.maxHeap)) 32 | elif len(self.maxHeap) < len(self.minHeap): 33 | heappush(self.maxHeap, -heappop(self.minHeap)) 34 | 35 | def findMedian(self): 36 | if len(self.maxHeap) == len(self.minHeap): 37 | return (-self.maxHeap[0] + self.minHeap[0]) / 2.0 38 | else: 39 | return -self.maxHeap[0] / 1.0 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /每日一题/316. Remove Duplicate Letters.md: -------------------------------------------------------------------------------- 1 | ## 316. Remove Duplicate Letters 2 | 3 | https://leetcode.com/problems/remove-duplicate-letters/ 4 | 5 | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. 6 | 7 | **Note:** This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: s = "bcabc" 15 | Output: "abc" 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: s = "cbacdcbc" 22 | Output: "acdb" 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - `1 <= s.length <= 104` 30 | - `s` consists of lowercase English letters. 31 | 32 | 33 | 34 | ### 代码 35 | 36 | ```python 37 | class Solution: 38 | def removeDuplicateLetters(self, s: str) -> str: 39 | if not s: 40 | return "" 41 | stack = [] 42 | seen = set() 43 | 44 | last_occur = {c: i for i, c in enumerate(s)} 45 | 46 | for i, c in enumerate(s): 47 | if c not in seen: 48 | while stack and c < stack[-1] and i < last_occur[stack[-1]]: 49 | seen.discard(stack.pop()) 50 | seen.add(c) 51 | stack.append(c) 52 | 53 | return "".join(stack) 54 | ``` 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /每日一题/347. Top K Frequent Elements.md: -------------------------------------------------------------------------------- 1 | ## 347. Top K Frequent Elements 2 | 3 | https://leetcode.com/problems/top-k-frequent-elements/ 4 | 5 | Given an integer array `nums` and an integer `k`, return *the* `k` *most frequent elements*. You may return the answer in **any order**. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: nums = [1,1,1,2,2,3], k = 2 13 | Output: [1,2] 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: nums = [1], k = 1 20 | Output: [1] 21 | ``` 22 | 23 | 24 | 25 | **Constraints:** 26 | 27 | - `1 <= nums.legth <= 105` 28 | - `k` is in the range `[1, the number of unique elements in the array]`. 29 | - It is **guaranteed** that the answer is **unique**. 30 | 31 | 32 | 33 | **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. 34 | 35 | 36 | 37 | ### 代码 38 | 39 | - 思路:计数排序 40 | - `cnt[x]` 表示`x`出现的次数,`f[v]` 表示出现次数为`v`的数字有多少个,`i`为出现次数排第 `k`的 `v`。 41 | - 因为 `f` 数组的下标对应频率从小到大,且一个长度为`n`的数组最多只能有一个数出现`n`次,所以我们从最大的下标开始往前遍历,累加元素个数,统计到第`k`个元素即可。 42 | 43 | ```python 44 | class Solution(object): 45 | def topKFrequent(self, nums, k): 46 | """ 47 | :type nums: List[int] 48 | :type k: int 49 | :rtype: List[int] 50 | """ 51 | cnt = defaultdict(int) 52 | res = [] 53 | n = len(nums) 54 | 55 | for x in nums: 56 | cnt[x] += 1 57 | 58 | f = [0] * (n + 1) 59 | for v in cnt.values(): 60 | f[v] += 1 61 | 62 | i, t = n, 0 63 | while t < k: 64 | t += f[i] 65 | i -= 1 66 | 67 | for x, v in cnt.items(): 68 | if v > i: 69 | res.append(x) 70 | 71 | return res 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /每日一题/354. Russian Doll Envelopes.md: -------------------------------------------------------------------------------- 1 | ## 354. Russian Doll Envelopes 2 | 3 | https://leetcode.com/problems/russian-doll-envelopes/ 4 | 5 | You have a number of envelopes with widths and heights given as a pair of integers `(w, h)`. One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. 6 | 7 | What is the maximum number of envelopes can you Russian doll? (put one inside other) 8 | 9 | **Note:** 10 | Rotation is not allowed. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: [[5,4],[6,4],[6,7],[2,3]] 16 | Output: 3 17 | Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). 18 | ``` 19 | 20 | 21 | 22 | ### 思路 23 | 24 | - LIS,最长上升子序列个数的经典问题,先对这些envelopes排序,宽度从小到大排,宽度相同的信封,高度按从高到低排序,然后用二分求LIS。 25 | 26 | - 注意,O(n^2)的DP求解会超时 27 | 28 | ### 代码 29 | 30 | ```python 31 | class Solution: 32 | def maxEnvelopes(self, arr: List[List[int]]) -> int: 33 | arr.sort(key=lambda x:(x[0], -x[1])) 34 | LIS = [] 35 | for x in arr: 36 | left, right = 0, len(LIS) 37 | x_height = x[1] 38 | 39 | while left < right: 40 | mid = left + right >> 1 41 | if LIS[mid] >= x_height: 42 | right = mid 43 | else: 44 | left = mid + 1 45 | 46 | if right == len(LIS): 47 | LIS.append(x_height) 48 | else: 49 | LIS[right] = x_height 50 | 51 | return len(LIS) 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /每日一题/392. Is Subsequence.md: -------------------------------------------------------------------------------- 1 | ## 392. Is Subsequence 2 | 3 | https://leetcode.com/problems/is-subsequence/ 4 | 5 | Given a string **s** and a string **t**, check if **s** is subsequence of **t**. 6 | 7 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `"ace"` is a subsequence of `"abcde"` while `"aec"` is not). 8 | 9 | **Follow up:** 10 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? 11 | 12 | **Credits:** 13 | Special thanks to [@pbrother](https://leetcode.com/pbrother/) for adding this problem and creating all test cases. 14 | 15 | 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: s = "abc", t = "ahbgdc" 21 | Output: true 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: s = "axc", t = "ahbgdc" 28 | Output: false 29 | ``` 30 | 31 | 32 | 33 | **Constraints:** 34 | 35 | - `0 <= s.length <= 100` 36 | - `0 <= t.length <= 10^4` 37 | - Both strings consists only of lowercase characters. 38 | 39 | 40 | 41 | ### 代码 42 | 43 | - 双指针,从头扫描一遍 t , 当 `t[i] == s[k]` , 移动 k , 最终判断k能不能走完 s. 44 | 45 | ```python 46 | class Solution: 47 | def isSubsequence(self, s: str, t: str) -> bool: 48 | k = 0 49 | for c in t: 50 | if k < len(s) and c == s[k]: 51 | k += 1 52 | return k == len(s) 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/406. Queue Reconstruction by Height.md: -------------------------------------------------------------------------------- 1 | ## 406. Queue Reconstruction by Height 2 | 3 | https://leetcode.com/problems/queue-reconstruction-by-height/ 4 | 5 | ### 题目 6 | 7 | Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers `(h, k)`, where `h` is the height of the person and `k` is the number of people in front of this person who have a height greater than or equal to `h`. Write an algorithm to reconstruct the queue. 8 | 9 | **Note:** 10 | The number of people is less than 1,100. 11 | 12 | **Example** 13 | 14 | ``` 15 | Input: 16 | [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 17 | 18 | Output: 19 | [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 20 | ``` 21 | 22 | ![pic](https://leetcode.com/problems/queue-reconstruction-by-height/Figures/406/input.png) 23 | 24 | ### 代码 25 | 26 | - people =【身高,index】,身高按**高到低**排序,index 从**小到大**排序。 27 | - people 排好序后,一个个按照自己的 index 插到 result 中即可。 28 | 29 | ```python 30 | class Solution: 31 | def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: 32 | 33 | # greedy + insert 34 | people.sort(key = lambda x: (-x[0], x[1])) 35 | res = [] 36 | 37 | for p in people: 38 | res.insert(p[1], p) 39 | return res 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /每日一题/409. Longest Palindrome.md: -------------------------------------------------------------------------------- 1 | ## 409. Longest Palindrome 2 | 3 | https://leetcode.com/problems/longest-palindrome/ 4 | 5 | > **Example:** 6 | > 7 | > ``` 8 | > Input: 9 | > "abccccdd" 10 | > 11 | > Output: 12 | > 7 13 | > 14 | > Explanation: 15 | > One longest palindrome that can be built is "dccaccd", whose length is 7. 16 | > ``` 17 | 18 | ### 代码 19 | 20 | ```python 21 | class Solution: 22 | def longestPalindrome(self, s: str) -> int: 23 | 24 | freq = defaultdict(int) 25 | for ch in s: 26 | if ch not in freq: 27 | freq[ch] = 0 28 | freq[ch] += 1 29 | 30 | count = 0 31 | 32 | for ch, v in sorted(freq.items(), key=lambda x:x[1]): 33 | count += v // 2 * 2 34 | if count % 2 == 0 and v % 2 == 1: 35 | count += 1 36 | 37 | return count 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /每日一题/41. First Missing Positive.md: -------------------------------------------------------------------------------- 1 | ## 41. First Missing Positive 2 | 3 | https://leetcode.com/problems/first-missing-positive/ 4 | 5 | Given an unsorted integer array, find the smallest missing positive integer. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,2,0] 11 | Output: 3 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: [3,4,-1,1] 18 | Output: 2 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: [7,8,9,11,12] 25 | Output: 1 26 | ``` 27 | 28 | **Follow up:** 29 | 30 | Your algorithm should run in *O*(*n*) time and uses constant extra space. 31 | 32 | 33 | 34 | ### 代码 35 | 36 | ```python 37 | class Solution(object): 38 | def firstMissingPositive(self, A): 39 | """ 40 | :type nums: List[int] 41 | :rtype: int 42 | """ 43 | A.append(0) 44 | n = len(A) 45 | for i in range(len(A)): 46 | if A[i] < 0 or A[i] >= n: 47 | A[i] = 0 48 | for i in range(len(A)): 49 | A[A[i] % n] += n 50 | for i in range(1, len(A)): 51 | if A[i] / n == 0: 52 | return i 53 | return n 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /每日一题/413. Arithmetic Slices.md: -------------------------------------------------------------------------------- 1 | ## 413. Arithmetic Slices 2 | 3 | https://leetcode.com/problems/arithmetic-slices/ 4 | 5 | A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. 6 | 7 | For example, these are arithmetic sequences: 8 | 9 | ``` 10 | 1, 3, 5, 7, 9 11 | 7, 7, 7, 7 12 | 3, -1, -5, -9 13 | ``` 14 | 15 | The following sequence is not arithmetic. 16 | 17 | ``` 18 | 1, 1, 2, 5, 7 19 | ``` 20 | 21 | A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N. 22 | 23 | A slice (P, Q) of the array A is called arithmetic if the sequence: 24 | A[P], A[P + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. 25 | 26 | The function should return the number of arithmetic slices in the array A. 27 | 28 | **Example:** 29 | 30 | ``` 31 | A = [1, 2, 3, 4] 32 | 33 | return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. 34 | ``` 35 | 36 | ### 代码 37 | 38 | - 动态规划 39 | 40 | ```java 41 | class Solution { 42 | public int numberOfArithmeticSlices(int[] A) { 43 | if (A == null || A.length < 3) return 0; 44 | int n = A.length; 45 | int[] f = new int[n]; 46 | int cnt = 0; 47 | for (int i = 2; i < n; i++) { 48 | if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { 49 | f[i] = 1 + f[i - 1]; 50 | cnt += f[i]; 51 | } 52 | } 53 | return cnt; 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/416. Partition Equal Subset Sum.md: -------------------------------------------------------------------------------- 1 | ## 416. Partition Equal Subset Sum 2 | 3 | https://leetcode.com/problems/partition-equal-subset-sum/ 4 | 5 | Given a **non-empty** array `nums` containing **only positive integers**, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: nums = [1,5,11,5] 13 | Output: true 14 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: nums = [1,2,3,5] 21 | Output: false 22 | Explanation: The array cannot be partitioned into equal sum subsets. 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - `1 <= nums.length <= 200` 30 | - `1 <= nums[i] <= 100` 31 | 32 | ### 代码 33 | 34 | - Python DFS + Memo 35 | 36 | ```python 37 | class Solution: 38 | def canPartition(self, nums: List[int]) -> bool: 39 | s, n, memo = sum(nums), len(nums), {0: True} 40 | if s & 1: return False 41 | nums.sort(reverse=True) 42 | def dfs(i, x): # x := remaining 43 | if x not in memo: 44 | memo[x] = False 45 | if x > 0: 46 | for j in range(i, n): 47 | if dfs(j+1, x-nums[j]): 48 | memo[x] = True 49 | break 50 | return memo[x] 51 | return dfs(0, s >> 1) 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /每日一题/42. Trapping Rain Water.md: -------------------------------------------------------------------------------- 1 | # 42. Trapping Rain Water 2 | 3 | https://leetcode.com/problems/trapping-rain-water/ 4 | 5 | Given *n* non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 6 | 7 | ![img](https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png) 8 | The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. **Thanks Marcos** for contributing this image! 9 | 10 | **Example:** 11 | 12 | ``` 13 | Input: [0,1,0,2,1,0,1,3,2,1,2,1] 14 | Output: 6 15 | ``` 16 | 17 | ### 代码 18 | 19 | ```java 20 | class Solution { 21 | public int trap(int[] height) { 22 | if (height == null || height.length < 3) { 23 | return 0; 24 | } 25 | int vol = 0; 26 | int left = 0, right = height.length - 1; 27 | int lmax = height[left]; 28 | int rmax = height[right]; 29 | 30 | while (left < right) { 31 | lmax = Math.max(lmax, height[left]); 32 | rmax = Math.max(rmax, height[right]); 33 | 34 | if (lmax <= rmax) { 35 | vol += lmax - height[left]; 36 | left++; 37 | } 38 | 39 | else { 40 | vol += rmax - height[right]; 41 | right--; 42 | } 43 | } 44 | return vol; 45 | } 46 | } 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /每日一题/434. Number of Segments in a String.md: -------------------------------------------------------------------------------- 1 | ## 434. Number of Segments in a String 2 | 3 | https://leetcode.com/problems/number-of-segments-in-a-string/ 4 | 5 | You are given a string `s`, return *the number of segments in the string*. 6 | 7 | A **segment** is defined to be a contiguous sequence of **non-space characters**. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: s = "Hello, my name is John" 15 | Output: 5 16 | Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: s = "Hello" 23 | Output: 1 24 | ``` 25 | 26 | **Example 3:** 27 | 28 | ``` 29 | Input: s = "love live! mu'sic forever" 30 | Output: 4 31 | ``` 32 | 33 | **Example 4:** 34 | 35 | ``` 36 | Input: s = "" 37 | Output: 0 38 | ``` 39 | 40 | 41 | 42 | **Constraints:** 43 | 44 | - `0 <= s.length <= 300` 45 | - `s` consists of lower-case and upper-case English letters, digits or one of the following characters `"!@#$%^&*()_+-=',.:"`. 46 | - The only space character in `s` is `' '`. 47 | 48 | 49 | 50 | ### 代码 51 | 52 | - 经典双指针 53 | 54 | ```java 55 | class Solution { 56 | public int countSegments(String ss) { 57 | int res = 0; 58 | char[] s = ss.toCharArray(); 59 | for (int i = 0; i < s.length; i++) { 60 | if (s[i] == ' ') continue; 61 | int j = i + 1; 62 | while (j < s.length && s[j] != ' ') 63 | j ++; 64 | res ++; 65 | i = j - 1; 66 | } 67 | return res; 68 | } 69 | } 70 | ``` 71 | 72 | -------------------------------------------------------------------------------- /每日一题/45.JumpGameII.md: -------------------------------------------------------------------------------- 1 | # 45. Jump Game II 2 | 3 | ## [题目](https://leetcode.com/problems/jump-game-ii/) 4 | 5 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 6 | 7 | Each element in the array represents your maximum jump length at that position. 8 | 9 | Your goal is to reach the last index in the minimum number of jumps. 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: [2,3,1,1,4] 15 | Output: 2 16 | Explanation: The minimum number of jumps to reach the last index is 2. 17 | Jump 1 step from index 0 to 1, then 3 steps to the last index. 18 | ``` 19 | 20 | ## 思路 21 | 22 | 动态规划,设三个变量:near,far,step 23 | 24 | - near : 初始值为0。表示需要跳跃的最小限值 25 | - far : 在当前位置能跳跃到最远的位置 26 | - step : 跳跃步数 27 | 28 | 注意: 29 | 30 | - 当index遍历到超过near的值时,需要step++,且将near的值更改为far的值,表示从当前到far这段距离不需要增加步数 31 | - 每次index遍历需要更新far 32 | 33 | ### 演示 34 | 35 | arr = [2, 3, 1, 1, 4] 36 | 37 | index=0, near=0, far=2, step=0 38 | 39 | index=1, near=2, far=4, step=1 40 | 41 | index=2, near=2, far=4, step=1 42 | 43 | index=3, near=4, far=4, step=2 44 | 45 | index=4, near=4, far=8, step=2 46 | 47 | ## 代码 48 | 49 | ```java 50 | // Source : https://leetcode.com/problems/jump-game-ii/ 51 | // Author : LLancelot 52 | // Date : 2020-07-16 53 | class Solution { 54 | public int jump(int[] nums) { 55 | int step = 0; 56 | int near = 0; 57 | int far = nums[0]; 58 | 59 | for (int i = 0; i < nums.length; i++) { 60 | if (i > near) { 61 | step++; 62 | near = far; 63 | } 64 | far = Math.max(far, i + nums[i]); 65 | } 66 | 67 | return step; 68 | } 69 | } 70 | ``` -------------------------------------------------------------------------------- /每日一题/456. 132 Pattern.md: -------------------------------------------------------------------------------- 1 | ## 456. 132 Pattern 2 | 3 | https://leetcode.com/problems/132-pattern/ 4 | 5 | Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`. 6 | 7 | Return *`true` if there is a **132 pattern** in `nums`, otherwise, return `false`.* 8 | 9 | **Follow up:** The `O(n^2)` is trivial, could you come up with the `O(n logn)` or the `O(n)` solution? 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [1,2,3,4] 17 | Output: false 18 | Explanation: There is no 132 pattern in the sequence. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: nums = [3,1,4,2] 25 | Output: true 26 | Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: nums = [-1,3,2,0] 33 | Output: true 34 | Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. 35 | ``` 36 | 37 | 38 | 39 | **Constraints:** 40 | 41 | - `n == nums.length` 42 | - `1 <= n <= 104` 43 | - `-109 <= nums[i] <= 109` 44 | 45 | 46 | 47 | ### 代码 48 | 49 | ```python 50 | class Solution: 51 | def find132pattern(self, A: List[int]) -> bool: 52 | if not A or len(A) < 3: 53 | return False 54 | min_list = list(itertools.accumulate(A, min)) 55 | stack, n = [], len(A) 56 | for i in range(n-1, -1, -1): 57 | if A[i] > min_list[i]: 58 | while stack and stack[-1] <= min_list[i]: 59 | stack.pop() 60 | if stack and A[i] > stack[-1]: 61 | return True 62 | stack.append(A[i]) 63 | return False 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/458. Poor Pigs (Hard).md: -------------------------------------------------------------------------------- 1 | ## 458. Poor Pigs (Hard) 2 | 3 | https://leetcode.com/problems/poor-pigs/ 4 | 5 | There are 1000 buckets, one and only one of them is poisonous, while the rest are filled with water. They all look identical. If a pig drinks the poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour? 6 | 7 | Answer this question, and write an algorithm for the general case. 8 | 9 | 10 | 11 | **General case:** 12 | 13 | If there are `n` buckets and a pig drinking poison will die within `m` minutes, how many pigs (`x`) you need to figure out the **poisonous** bucket within `p` minutes? There is exactly one bucket with poison. 14 | 15 | 16 | 17 | **Note:** 18 | 19 | 1. A pig can be allowed to drink simultaneously on as many buckets as one would like, and the feeding takes no time. 20 | 2. After a pig has instantly finished drinking buckets, there has to be a **cool down time** of *m* minutes. During this time, only observation is allowed and no feedings at all. 21 | 3. Any given bucket can be sampled an infinite number of times (by an unlimited number of pigs). 22 | 23 | 24 | 25 | ### 代码 26 | 27 | ```cpp 28 | class Solution { 29 | public: 30 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 31 | return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1)); 32 | } 33 | }; 34 | ``` 35 | 36 | -------------------------------------------------------------------------------- /每日一题/459. Repeated Substring Pattern.md: -------------------------------------------------------------------------------- 1 | ## 459. Repeated Substring Pattern 2 | 3 | https://leetcode.com/problems/repeated-substring-pattern/ 4 | 5 | Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: "abab" 13 | Output: True 14 | Explanation: It's the substring "ab" twice. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: "aba" 21 | Output: False 22 | ``` 23 | 24 | **Example 3:** 25 | 26 | ``` 27 | Input: "abcabcabcabc" 28 | Output: True 29 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) 30 | ``` 31 | 32 | ### 代码 33 | 34 | ```python 35 | class Solution: 36 | def repeatedSubstringPattern(self, str: str) -> bool: 37 | if not str: 38 | return False 39 | 40 | ss = (str + str)[1:-1] 41 | return ss.find(str) != -1 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /每日一题/468. Validate IP Address.md: -------------------------------------------------------------------------------- 1 | ## 468. Validate IP Address 2 | 3 | https://leetcode.com/problems/validate-ip-address/ 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: IP = "172.16.254.1" 9 | Output: "IPv4" 10 | Explanation: This is a valid IPv4 address, return "IPv4". 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334" 17 | Output: "IPv6" 18 | Explanation: This is a valid IPv6 address, return "IPv6". 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: IP = "256.256.256.256" 25 | Output: "Neither" 26 | Explanation: This is neither a IPv4 address nor a IPv6 address. 27 | ``` 28 | 29 | **Example 4:** 30 | 31 | ``` 32 | Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" 33 | Output: "Neither" 34 | ``` 35 | 36 | **Example 5:** 37 | 38 | ``` 39 | Input: IP = "1e1.4.5.6" 40 | Output: "Neither" 41 | ``` 42 | 43 | ### 代码 44 | 45 | ```python 46 | class Solution(object): 47 | def validIPAddress(self, IP): 48 | """ 49 | :type IP: str 50 | :rtype: str 51 | """ 52 | 53 | isValid = True 54 | v4 = IP.split('.') 55 | if len(v4) == 4: 56 | for x in v4: 57 | if x == '' or (x[0] == '0' and len(x) != 1) or not x.isdigit() or int(x) > 255: 58 | isValid = False 59 | break 60 | if isValid: 61 | return 'IPv4' 62 | 63 | v6 = IP.split(':') 64 | if len(v6) == 8: 65 | for x in v6: 66 | if x == '' or len(x) > 4 or not all(c in hexdigits for c in x): 67 | isValid = False 68 | break 69 | if isValid: 70 | return 'IPv6' 71 | 72 | return 'Neither' 73 | ``` 74 | 75 | -------------------------------------------------------------------------------- /每日一题/470. Implement Rand10() Using Rand7().md: -------------------------------------------------------------------------------- 1 | ## 470. Implement Rand10() Using Rand7() 2 | 3 | Given a function `rand7` which generates a uniform random integer in the range 1 to 7, write a function `rand10` which generates a uniform random integer in the range 1 to 10. 4 | 5 | Do NOT use system's `Math.random()`. 6 | 7 | ### 代码 8 | 9 | ```java 10 | /** 11 | * The rand7() API is already defined in the parent class SolBase. 12 | * public int rand7(); 13 | * @return a random integer in the range 1 to 7 14 | */ 15 | class Solution extends SolBase { 16 | public int rand10() { 17 | int rand40 = 40; 18 | while (rand40 >= 40) { 19 | rand40 = (rand7() - 1) * 7 + rand7() - 1; 20 | } 21 | return rand40 % 10 + 1; 22 | } 23 | } 24 | ``` 25 | 26 | -------------------------------------------------------------------------------- /每日一题/472. Concatenated Words.md: -------------------------------------------------------------------------------- 1 | ## 472. Concatenated Words (Hard) 2 | 3 | https://leetcode.com/problems/concatenated-words/ 4 | 5 | Given an array of strings `words` (**without duplicates**), return *all the **concatenated words** in the given list of* `words`. 6 | 7 | A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words in the given array. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] 15 | Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] 16 | Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 17 | "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; 18 | "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: words = ["cat","dog","catdog"] 25 | Output: ["catdog"] 26 | ``` 27 | 28 | ### 代码 29 | 30 | - 动态规划 + HashSet 31 | 32 | ```python 33 | class Solution: 34 | def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]: 35 | hs = set() 36 | for word in words: 37 | hs.add(word) 38 | res = [] 39 | 40 | 41 | def check(word): 42 | n = len(word) 43 | f = [float('-inf')] * (n + 1) 44 | f[0] = 0 45 | for i in range(n + 1): 46 | if f[i] < 0: continue 47 | for j in range(n - i, 0, -1): 48 | if word[i:i+j] in hs: 49 | f[i + j] = max(f[i + j], f[i] + 1) 50 | if f[n] > 1: 51 | return True 52 | return False 53 | 54 | 55 | for word in words: 56 | if (check(word)): 57 | res.append(word) 58 | return res 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /每日一题/482.LicenseKeyFormatting.md: -------------------------------------------------------------------------------- 1 | # 482. License Key Formatting 2 | 3 | ## [题目](https://leetcode.com/problems/license-key-formatting/) 4 | 5 | You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. 6 | 7 | Given a number K, we would want to reformat the strings such that each group contains *exactly* K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. 8 | 9 | Given a non-empty string S and a number K, format the string according to the rules described above. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: S = "5F3Z-2e-9-w", K = 4 15 | 16 | Output: "5F3Z-2E9W" 17 | 18 | Explanation: The string S has been split into two parts, each part has 4 characters. 19 | Note that the two extra dashes are not needed and can be removed. 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: S = "2-5g-3-J", K = 2 26 | 27 | Output: "2-5G-3J" 28 | 29 | Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. 30 | ``` 31 | 32 | ## 思路 33 | 34 | - 先把字符串按逆序方向,去掉连接符,即将 “-” 替换成空串。 35 | - 根据长度 K 截取 36 | 37 | ## 代码 38 | 39 | ```python 40 | # Source : https://leetcode.com/problems/license-key-formatting/ 41 | # Author : LLancelot 42 | # Date : 2020-07-09 43 | 44 | class Solution: 45 | def licenseKeyFormatting(self, S, K): 46 | """ 47 | :type S: str 48 | :type K: int 49 | :rtype: str 50 | """ 51 | S = S.replace("-", "").upper()[::-1] # 先逆序 52 | return '-'.join(S[i:i+K] for i in range(0, len(S), K))[::-1] # 截取后再逆序输出 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/498. Diagonal Traverse.md: -------------------------------------------------------------------------------- 1 | # 498. Diagonal Traverse 2 | 3 | https://leetcode.com/problems/diagonal-traverse/ 4 | 5 | Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. 6 | 7 | 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: 13 | [ 14 | [ 1, 2, 3 ], 15 | [ 4, 5, 6 ], 16 | [ 7, 8, 9 ] 17 | ] 18 | 19 | Output: [1,2,4,7,5,3,6,8,9] 20 | 21 | Explanation: 22 | ``` 23 | 24 | img 25 | 26 | **Note:** 27 | 28 | The total number of elements of the given matrix will not exceed 10,000. 29 | 30 | 31 | 32 | ## 代码 33 | 34 | ```java 35 | class Solution { 36 | public int[] findDiagonalOrder(int[][] matrix) { 37 | if (matrix.length == 0 || matrix[0].length == 0) 38 | return new int[]{}; 39 | int rows = matrix.length, cols = matrix[0].length; 40 | int[] res = new int[rows * cols]; 41 | int numOfTraverse = rows + cols - 1; 42 | int index = 0; 43 | for (int i = 0; i < numOfTraverse; i++) { 44 | if (i % 2 == 0) { 45 | int x = i < rows ? i : rows - 1; 46 | int y = i < rows ? 0 : i - (rows - 1); 47 | while (x >= 0 && y < cols) { 48 | res[index++] = matrix[x--][y++]; 49 | } 50 | } else { 51 | int x = i < cols ? 0 : i - (cols - 1); 52 | int y = i < cols ? i : cols - 1; 53 | while (y >= 0 && x < rows) { 54 | res[index++] = matrix[x++][y--]; 55 | } 56 | } 57 | } 58 | return res; 59 | } 60 | } 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/532. K-diff Pairs in an Array.md: -------------------------------------------------------------------------------- 1 | ## 532. K-diff Pairs in an Array 2 | 3 | https://leetcode.com/problems/k-diff-pairs-in-an-array/ 4 | 5 | Given an array of integers `nums` and an integer `k`, return *the number of **unique** k-diff pairs in the array*. 6 | 7 | A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: 8 | 9 | - `0 <= i, j < nums.length` 10 | - `i != j` 11 | - `a <= b` 12 | - `b - a == k` 13 | 14 | 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [3,1,4,1,5], k = 2 20 | Output: 2 21 | Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). 22 | Although we have two 1s in the input, we should only return the number of unique pairs. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: nums = [1,2,3,4,5], k = 1 29 | Output: 4 30 | Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: nums = [1,3,1,5,4], k = 0 37 | Output: 1 38 | Explanation: There is one 0-diff pair in the array, (1, 1). 39 | ``` 40 | 41 | **Example 4:** 42 | 43 | ``` 44 | Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3 45 | Output: 2 46 | ``` 47 | 48 | **Example 5:** 49 | 50 | ``` 51 | Input: nums = [-1,-2,-3], k = 1 52 | Output: 2 53 | ``` 54 | 55 | 56 | 57 | **Constraints:** 58 | 59 | - `1 <= nums.length <= 104` 60 | - `-107 <= nums[i] <= 107` 61 | - `0 <= k <= 107` 62 | 63 | 64 | 65 | ### 代码 66 | 67 | ```python 68 | class Solution: 69 | def findPairs(self, nums: List[int], k: int) -> int: 70 | ret = 0 71 | c = collections.Counter(nums) 72 | 73 | for key in c: 74 | if k > 0 and key + k in c: 75 | ret += 1 76 | if k == 0 and c[key] > 1: 77 | ret += 1 78 | return ret 79 | ``` 80 | 81 | -------------------------------------------------------------------------------- /每日一题/538. Convert BST to Greater Tree.md: -------------------------------------------------------------------------------- 1 | ## 538. Convert BST to Greater Tree 2 | 3 | https://leetcode.com/problems/convert-bst-to-greater-tree/ 4 | 5 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 6 | 7 | As a reminder, a *binary search tree* is a tree that satisfies these constraints: 8 | 9 | - The left subtree of a node contains only nodes with keys **less than** the node's key. 10 | - The right subtree of a node contains only nodes with keys **greater than** the node's key. 11 | - Both the left and right subtrees must also be binary search trees. 12 | 13 | **Note:** This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ 14 | 15 | 16 | 17 | **Example 1:** 18 | 19 | ![img](https://assets.leetcode.com/uploads/2019/05/02/tree.png) 20 | 21 | ``` 22 | Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] 23 | Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] 24 | ``` 25 | 26 | 27 | 28 | ### 代码 29 | 30 | ```java 31 | class Solution { 32 | int total = 0; 33 | public TreeNode convertBST(TreeNode root) { 34 | if (root == null) return null; 35 | change(root); 36 | return root; 37 | } 38 | public void change(TreeNode root) { 39 | if (root == null) return; 40 | change(root.right); 41 | total += root.val; 42 | root.val = total; 43 | change(root.left); 44 | } 45 | } 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /每日一题/556. Next Greater Element III.md: -------------------------------------------------------------------------------- 1 | ## 556. Next Greater Element III 2 | 3 | https://leetcode.com/problems/next-greater-element-iii/ 4 | 5 | Given a positive integer `n`, find *the smallest integer which has exactly the same digits existing in the integer* `n` *and is greater in value than* `n`. If no such positive integer exists, return `-1`. 6 | 7 | **Note** that the returned integer should fit in **32-bit integer**, if there is a valid answer but it does not fit in **32-bit integer**, return `-1`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: n = 12 15 | Output: 21 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: n = 21 22 | Output: -1 23 | ``` 24 | 25 | **Constraints:** 26 | 27 | - `1 <= n <= 231 - 1` 28 | 29 | ### 代码 30 | 31 | - Same idea, refer to [31. Next Permutation](https://leetcode.com/problems/next-permutation/) 32 | 33 | ```python 34 | class Solution(object): 35 | def nextGreaterElement(self, N): 36 | """ 37 | :type n: int 38 | :rtype: int 39 | """ 40 | return nextGreaterElement(N) 41 | 42 | def nextGreaterElement(N): 43 | A = list(map(int, list(str(N)))) 44 | n = len(A) 45 | i = n - 1 46 | while i > 0 and A[i-1] >= A[i]: 47 | i -= 1 48 | if i == 0: 49 | # digits in descending order, like "4321", return -1. 50 | return -1 51 | 52 | if i > 0: 53 | j = i + 1 54 | while j < n and A[j] > A[i-1]: 55 | j += 1 56 | # swap 57 | A[i - 1], A[j - 1] = A[j - 1], A[i - 1] 58 | A[i:] = A[i:][::-1] 59 | res = int("".join(list(map(str, A)))) 60 | return res if res <= ((1<<31)-1) else -1 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/593. Valid Square.md: -------------------------------------------------------------------------------- 1 | ## 593. Valid Square 2 | 3 | https://leetcode.com/problems/valid-square/ 4 | 5 | Given the coordinates of four points in 2D space, return whether the four points could construct a square. 6 | 7 | The coordinate (x,y) of a point is represented by an integer array with two integers. 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 13 | Output: True 14 | ``` 15 | 16 | 17 | 18 | Note: 19 | 20 | 1. All the input integers are in the range [-10000, 10000]. 21 | 2. A valid square has four equal sides with positive length and four equal angles (90-degree angles). 22 | 3. Input points have no order. 23 | 24 | 25 | 26 | ### 代码 27 | 28 | ```python 29 | class Solution(object): 30 | def validSquare(self, p1, p2, p3, p4): 31 | if p1==p2==p3==p4:return False 32 | def dist(x,y): 33 | return (x[0]-y[0])**2+(x[1]-y[1])**2 34 | ls=[dist(p1,p2),dist(p1,p3),dist(p1,p4),dist(p2,p3),dist(p2,p4),dist(p3,p4)] 35 | ls.sort() 36 | if ls[0]==ls[1]==ls[2]==ls[3]: 37 | if ls[4]==ls[5]: 38 | return True 39 | return False 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /每日一题/594. Longest Harmonious Subsequence.md: -------------------------------------------------------------------------------- 1 | ## 594. Longest Harmonious Subsequence 2 | 3 | https://leetcode.com/problems/longest-harmonious-subsequence/ 4 | 5 | We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. 6 | 7 | Given an integer array `nums`, return *the length of its longest harmonious subsequence among all its possible subsequences*. 8 | 9 | A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [1,3,2,2,5,2,3,7] 17 | Output: 5 18 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: nums = [1,2,3,4] 25 | Output: 2 26 | ``` 27 | 28 | **Example 3:** 29 | 30 | ``` 31 | Input: nums = [1,1,1,1] 32 | Output: 0 33 | ``` 34 | 35 | 36 | 37 | **Constraints:** 38 | 39 | - `1 <= nums.length <= 2 * 10^4` 40 | - `-10^9 <= nums[i] <= 10^9` 41 | 42 | ### 代码 43 | 44 | ```java 45 | class Solution { 46 | public int findLHS(int[] nums) { 47 | if (nums.length == 1) 48 | return 0; 49 | HashMap h = new HashMap<>(); 50 | for (int x : nums) { 51 | h.put(x, h.getOrDefault(x, 0) + 1); 52 | } 53 | int maxLen = 0; 54 | for (int x : h.keySet()) { 55 | if (h.containsKey(x - 1)) 56 | maxLen = Math.max(maxLen, h.get(x - 1) + h.get(x)); 57 | } 58 | return maxLen; 59 | } 60 | } 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/624. Maximum Distance in Arrays.md: -------------------------------------------------------------------------------- 1 | ## 624. Maximum Distance in Arrays 2 | 3 | https://leetcode.com/problems/maximum-distance-in-arrays/ 4 | 5 | Given `m` arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers `a` and `b` to be their absolute difference `|a-b|`. Your task is to find the maximum distance. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 11 | [[1,2,3], 12 | [4,5], 13 | [1,2,3]] 14 | Output: 4 15 | Explanation: 16 | One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. 17 | ``` 18 | 19 | 20 | 21 | **Note:** 22 | 23 | 1. Each given array will have at least 1 number. There will be at least two non-empty arrays. 24 | 2. The total number of the integers in **all** the `m` arrays will be in the range of [2, 10000]. 25 | 3. The integers in the `m` arrays will be in the range of [-10000, 10000]. 26 | 27 | ```python 28 | class Solution: 29 | def maxDistance(self, arrays: List[List[int]]) -> int: 30 | min_num = collections.defaultdict(list) 31 | max_num = collections.defaultdict(list) 32 | i = 0 33 | distance = 0 34 | for array in arrays: 35 | min_num[array[0]].append(i) 36 | max_num[array[-1]].append(i) 37 | i += 1 38 | 39 | for i in min_num: 40 | for j in max_num: 41 | if (j - i) > distance: 42 | if min_num[i] != max_num[j]: 43 | distance = j - i 44 | elif len(min_num[i]) > 1: 45 | distance = j - i 46 | return distance 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /每日一题/637. Average of Levels in Binary Tree.md: -------------------------------------------------------------------------------- 1 | ## 637. Average of Levels in Binary Tree 2 | 3 | Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 9 | 3 10 | / \ 11 | 9 20 12 | / \ 13 | 15 7 14 | Output: [3, 14.5, 11] 15 | Explanation: 16 | 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]. 17 | ``` 18 | 19 | 20 | 21 | **Note:** 22 | 23 | 1. The range of node's value is in the range of 32-bit signed integer. 24 | 25 | ### 代码 26 | 27 | - BFS 28 | 29 | ```java 30 | class Solution { 31 | public List averageOfLevels(TreeNode root) { 32 | List res = new ArrayList<>(); 33 | Deque q = new ArrayDeque<>(); 34 | if (root == null) return res; 35 | q.offer(root); 36 | while (!q.isEmpty()) { 37 | int qsize = q.size(); 38 | double avg = 0; 39 | int cnt = 0; 40 | for (int i = 0; i < qsize; i++) { 41 | TreeNode node = q.poll(); 42 | avg += node.val; 43 | cnt ++; 44 | if (node.left != null) q.offer(node.left); 45 | if (node.right != null) q.offer(node.right); 46 | } 47 | res.add(avg/cnt); 48 | } 49 | return res; 50 | } 51 | 52 | } 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/645. Set Mismatch.md: -------------------------------------------------------------------------------- 1 | ## 645. Set Mismatch 2 | 3 | https://leetcode.com/problems/set-mismatch/ 4 | 5 | You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. 6 | 7 | You are given an integer array `nums` representing the data status of this set after the error. 8 | 9 | Find the number that occurs twice and the number that is missing and return *them in the form of an array*. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [1,2,2,4] 17 | Output: [2,3] 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: nums = [1,1] 24 | Output: [1,2] 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - `2 <= nums.length <= 104` 32 | - `1 <= nums[i] <= 104` 33 | 34 | ### 代码 35 | 36 | ```java 37 | class Solution { 38 | public int[] findErrorNums(int[] nums) { 39 | boolean[] f = new boolean[10010]; 40 | int[] res = new int[2]; 41 | for (int x : nums) { 42 | if (f[x]) { 43 | res[0] = x; 44 | } 45 | f[x] = true; 46 | } 47 | for (int x = 1; x < 10010; x++) 48 | if (!f[x]) { 49 | res[1] = x; break; 50 | } 51 | return res; 52 | } 53 | } 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /每日一题/647. Palindromic Substrings.md: -------------------------------------------------------------------------------- 1 | ## 647. Palindromic Substrings 2 | 3 | https://leetcode.com/problems/palindromic-substrings/ 4 | 5 | Given a string, your task is to count how many palindromic substrings in this string. 6 | 7 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: "abc" 13 | Output: 3 14 | Explanation: Three palindromic strings: "a", "b", "c". 15 | ``` 16 | 17 | 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: "aaa" 23 | Output: 6 24 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 25 | ``` 26 | 27 | 28 | 29 | **Note:** 30 | 31 | 1. The input string length won't exceed 1000. 32 | 33 | 34 | 35 | ### 代码 36 | 37 | ```python 38 | class Solution: 39 | def countSubstrings(self, s: str) -> int: 40 | 41 | def helper(s, start, end): 42 | count = 0 43 | while start >= 0 and end < len(s) and s[start] == s[end]: 44 | count += 1 45 | start -= 1 46 | end += 1 47 | return count 48 | 49 | count = 0 50 | for i in range(len(s)): 51 | count += helper(s, i, i) + helper(s, i, i+1) 52 | return count 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/661. Image Smoother.md: -------------------------------------------------------------------------------- 1 | ## 661. Image Smoother 2 | 3 | https://leetcode.com/problems/image-smoother/ 4 | 5 | Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 11 | [[1,1,1], 12 | [1,0,1], 13 | [1,1,1]] 14 | Output: 15 | [[0, 0, 0], 16 | [0, 0, 0], 17 | [0, 0, 0]] 18 | Explanation: 19 | For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 20 | For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 21 | For the point (1,1): floor(8/9) = floor(0.88888889) = 0 22 | ``` 23 | 24 | 25 | 26 | **Note:** 27 | 28 | 1. The value in the given matrix is in the range of [0, 255]. 29 | 2. The length and width of the given matrix are in the range of [1, 150]. 30 | 31 | ### 代码 32 | 33 | ```java 34 | class Solution { 35 | public int[][] imageSmoother(int[][] M) { 36 | int n = M.length, m = M[0].length; 37 | int[][] res = new int[n][m]; 38 | int[] dirs = {1, 0, -1, 0, 1, 1, -1, -1, 1}; 39 | for (int i = 0; i < n; i++) { 40 | for (int j = 0; j < m; j++) { 41 | int val = M[i][j]; 42 | int cnt = 1; 43 | for (int d = 0; d < dirs.length - 1; d++) { 44 | int x = i + dirs[d], y = j + dirs[d + 1]; 45 | if (x < 0 || y < 0 || x >= n || y >= m) 46 | continue; 47 | val += M[x][y]; 48 | cnt++; 49 | } 50 | res[i][j] = val / cnt; 51 | } 52 | } 53 | return res; 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/673. Number of Longest Increasing Subsequence.md: -------------------------------------------------------------------------------- 1 | ## 673. Number of Longest Increasing Subsequence 2 | 3 | https://leetcode.com/problems/number-of-longest-increasing-subsequence/ 4 | 5 | Given an integer array `nums`, return *the number of longest increasing subsequences.* 6 | 7 | **Notice** that the sequence has to be **strictly** increasing. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: nums = [1,3,5,4,7] 15 | Output: 2 16 | Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: nums = [2,2,2,2,2] 23 | Output: 5 24 | Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - `1 <= nums.length <= 2000` 32 | - `-106 <= nums[i] <= 106` 33 | 34 | ### 代码 35 | 36 | - `f[i]` 记录以`nums[i]`结尾的最长上升子序列的长度,`g[i]`记录以`nums[i]`结尾的LIS个数。 37 | 38 | ```cpp 39 | class Solution { 40 | public: 41 | int findNumberOfLIS(vector& nums) { 42 | int n = nums.size(); 43 | vector f(n), g(n); 44 | int maxl = 0, cnt = 0; 45 | for (int i = 0; i < n; i++) { 46 | f[i] = g[i] = 1; 47 | for (int j = 0; j < i; j++ ) { 48 | if (nums[j] < nums[i]) { 49 | if (f[i] < f[j] + 1) f[i] = f[j] + 1, g[i] = g[j]; 50 | else if (f[i] == f[j] + 1) g[i] += g[j]; 51 | } 52 | } 53 | if (maxl < f[i]) maxl = f[i], cnt = g[i]; 54 | else if (maxl == f[i]) cnt += g[i]; 55 | } 56 | return cnt; 57 | } 58 | }; 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /每日一题/680. Valid Palindrome II.md: -------------------------------------------------------------------------------- 1 | ## 680. Valid Palindrome II 2 | 3 | https://leetcode.com/problems/valid-palindrome-ii/ 4 | 5 | Given a non-empty string `s`, you may delete **at most** one character. Judge whether you can make it a palindrome. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: "aba" 11 | Output: True 12 | ``` 13 | 14 | 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: "abca" 20 | Output: True 21 | Explanation: You could delete the character 'c'. 22 | ``` 23 | 24 | ### 代码 25 | 26 | - For example, s = "acbba", whenever we find mismatch, we need to check the part "cbb", if "bb" or "cb" is palindrome (delete **one** left char or right char) 27 | 28 | ```python 29 | class Solution(object): 30 | def validPalindrome(self, s): 31 | """ 32 | :type s: str 33 | :rtype: bool 34 | """ 35 | n = len(s) 36 | l, r = 0, n - 1 37 | while l < r: 38 | if s[l] != s[r]: 39 | extract_left = s[l+1:r+1] 40 | extract_right = s[l:r] 41 | return extract_left == extract_left[::-1] or \ 42 | extract_right == extract_right[::-1] 43 | else: 44 | l, r = l + 1, r - 1 45 | return True 46 | ``` 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /每日一题/693. Binary Number with Alternating Bits.md: -------------------------------------------------------------------------------- 1 | ## 693. Binary Number with Alternating Bits 2 | 3 | https://leetcode.com/problems/binary-number-with-alternating-bits/ 4 | 5 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: n = 5 13 | Output: true 14 | Explanation: The binary representation of 5 is: 101 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: n = 7 21 | Output: false 22 | Explanation: The binary representation of 7 is: 111. 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: n = 11 29 | Output: false 30 | Explanation: The binary representation of 11 is: 1011. 31 | ``` 32 | 33 | **Example 4:** 34 | 35 | ``` 36 | Input: n = 10 37 | Output: true 38 | Explanation: The binary representation of 10 is: 1010. 39 | ``` 40 | 41 | **Example 5:** 42 | 43 | ``` 44 | Input: n = 3 45 | Output: false 46 | ``` 47 | 48 | 49 | 50 | **Constraints:** 51 | 52 | - `1 <= n <= 2^31 - 1` 53 | 54 | ### 代码 55 | 56 | ```java 57 | class Solution { 58 | public boolean hasAlternatingBits(int n) { 59 | for (int i = 1; 1l << i <= n; i++) { 60 | int a = (n >> i - 1) & 1; 61 | int b = (n >> i) & 1; 62 | if (a == b) return false; 63 | } 64 | return true; 65 | } 66 | } 67 | ``` 68 | 69 | -------------------------------------------------------------------------------- /每日一题/739. Daily Temperatures.md: -------------------------------------------------------------------------------- 1 | ## 739. Daily Temperatures 2 | 3 | https://leetcode.com/problems/daily-temperatures/ 4 | 5 | Given an array of integers `temperatures` represents the daily temperatures, return *an array* `answer` *such that* `answer[i]` *is the number of days you have to wait after the* `ith` *day to get a warmer temperature*. If there is no future day for which this is possible, keep `answer[i] == 0` instead. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: temperatures = [73,74,75,71,69,72,76,73] 13 | Output: [1,1,4,2,1,1,0,0] 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: temperatures = [30,40,50,60] 20 | Output: [1,1,1,0] 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: temperatures = [30,60,90] 27 | Output: [1,1,0] 28 | ``` 29 | 30 | 31 | 32 | **Constraints:** 33 | 34 | - `1 <= temperatures.length <= 105` 35 | - `30 <= temperatures[i] <= 100` 36 | 37 | ### 代码 38 | 39 | ```java 40 | class Solution { 41 | public int[] dailyTemperatures(int[] tmp) { 42 | int n = tmp.length; 43 | int[] res = new int[n]; 44 | Deque stack = new ArrayDeque<>(); 45 | for (int i = 0; i < n; i++) { 46 | int cur = tmp[i]; 47 | while (!stack.isEmpty() && tmp[stack.peek()] < cur) { 48 | int top = stack.pop(); 49 | res[top] = i - top; 50 | } 51 | stack.push(i); 52 | } 53 | return res; 54 | } 55 | } 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /每日一题/743. Network Delay Time.md: -------------------------------------------------------------------------------- 1 | ## 743. Network Delay Time 2 | 3 | https://leetcode.com/problems/network-delay-time/ 4 | 5 | There are `N` network nodes, labelled `1` to `N`. 6 | 7 | Given `times`, a list of travel times as **directed** edges `times[i] = (u, v, w)`, where `u` is the source node, `v` is the target node, and `w` is the time it takes for a signal to travel from source to target. 8 | 9 | Now, we send a signal from a certain node `K`. How long will it take for all nodes to receive the signal? If it is impossible, return `-1`. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ![img](https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png) 16 | 17 | ``` 18 | Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2 19 | Output: 2 20 | ``` 21 | 22 | 23 | 24 | ### 代码 25 | 26 | - Dijkstra 27 | 28 | ```python 29 | class Solution(object): 30 | def networkDelayTime(self, times, N, src): 31 | """ 32 | :type times: List[List[int]] 33 | :type N: int 34 | :type src: int 35 | :rtype: int 36 | """ 37 | graph = defaultdict(list) 38 | for start, end, time in times: 39 | graph[start].append([end, time]) 40 | # heap := distance from src to current vertex 41 | heap = [(0, src)] 42 | visited = {} 43 | 44 | while heap: 45 | dist, node = heappop(heap) 46 | if node in visited: 47 | continue 48 | visited[node] = dist 49 | for nb, nb_dist in graph[node]: 50 | heappush(heap, (dist + nb_dist, nb)) 51 | 52 | return max(visited.values()) if len(visited) == N else -1 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/763. Partition Labels.md: -------------------------------------------------------------------------------- 1 | ## 763. Partition Labels 2 | 3 | A string `S` of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: S = "ababcbacadefegdehijhklij" 9 | Output: [9,7,8] 10 | Explanation: 11 | The partition is "ababcbaca", "defegde", "hijhklij". 12 | This is a partition so that each letter appears in at most one part. 13 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. 14 | ``` 15 | 16 | #### 代码 17 | 18 | ```python 19 | class Solution(object): 20 | def partitionLabels(self, S): 21 | """ 22 | :type S: str 23 | :rtype: List[int] 24 | """ 25 | lastIndex = [0] * 128 26 | n = len(S) 27 | for i in range(n): 28 | lastIndex[ord(S[i])] = i 29 | 30 | start, end, res = 0, 0, [] 31 | for i in range(n): 32 | end = max(end, lastIndex[ord(S[i])]) 33 | if i == end: 34 | res.append(end - start + 1) 35 | start = end + 1 36 | 37 | return res 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /每日一题/784. Letter Case Permutation.md: -------------------------------------------------------------------------------- 1 | ## 784. Letter Case Permutation 2 | 3 | https://leetcode.com/problems/letter-case-permutation/ 4 | 5 | Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. 6 | 7 | Return *a list of all possible strings we could create*. You can return the output in **any order**. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: S = "a1b2" 15 | Output: ["a1b2","a1B2","A1b2","A1B2"] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: S = "3z4" 22 | Output: ["3z4","3Z4"] 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: S = "12345" 29 | Output: ["12345"] 30 | ``` 31 | 32 | **Example 4:** 33 | 34 | ``` 35 | Input: S = "0" 36 | Output: ["0"] 37 | ``` 38 | 39 | 40 | 41 | **Constraints:** 42 | 43 | - `S` will be a string with length between `1` and `12`. 44 | - `S` will consist only of letters or digits. 45 | 46 | ### 代码 47 | 48 | ```cpp 49 | class Solution { 50 | void backtrack(string &s, int i, vector &res) { 51 | if (i == s.size()) { 52 | res.push_back(s); 53 | return; 54 | } 55 | backtrack(s, i + 1, res); 56 | if (isalpha(s[i])) { 57 | // toggle case 58 | s[i] ^= (1 << 5); 59 | backtrack(s, i + 1, res); 60 | } 61 | } 62 | public: 63 | vector letterCasePermutation(string S) { 64 | vector res; 65 | backtrack(S, 0, res); 66 | return res; 67 | } 68 | }; 69 | ``` 70 | 71 | -------------------------------------------------------------------------------- /每日一题/82. Remove Duplicates from Sorted List II.md: -------------------------------------------------------------------------------- 1 | ## 82. Remove Duplicates from Sorted List II 2 | 3 | https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 4 | 5 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only *distinct* numbers from the original list. 6 | 7 | Return the linked list sorted as well. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: 1->2->3->3->4->4->5 13 | Output: 1->2->5 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: 1->1->1->2->3 20 | Output: 2->3 21 | ``` 22 | 23 | ### 代码 24 | 25 | ```python 26 | class Solution: 27 | def deleteDuplicates(self, head: ListNode) -> ListNode: 28 | dummy = ListNode(0, head) 29 | # predecessor always points to the last non-duplicate element 30 | pred = dummy 31 | 32 | while head: 33 | if head.next and head.val == head.next.val: 34 | while head.next and head.val == head.next.val: # keep skipping 35 | head = head.next 36 | 37 | pred.next = head.next # here, head.next is no longer the duplicate 38 | 39 | else: 40 | pred = pred.next 41 | 42 | head = head.next # move to next element 43 | 44 | return dummy.next 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /每日一题/821. Shortest Distance to a Character.md: -------------------------------------------------------------------------------- 1 | ## 821. Shortest Distance to a Character 2 | 3 | https://leetcode.com/problems/shortest-distance-to-a-character/ 4 | 5 | Given a string `s` and a character `c` that occurs in `s`, return *an array of integers `answer` where* `answer.length == s.length` *and* `answer[i]` *is the shortest distance from* `s[i]` *to the character* `c` *in* `s`. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: s = "loveleetcode", c = "e" 13 | Output: [3,2,1,0,1,0,0,1,2,2,1,0] 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: s = "aaab", c = "b" 20 | Output: [3,2,1,0] 21 | ``` 22 | 23 | 24 | 25 | **Constraints:** 26 | 27 | - `1 <= s.length <= 104` 28 | - `s[i]` and `c` are lowercase English letters. 29 | - `c` occurs at least once in `s`. 30 | 31 | 32 | 33 | ### 代码 34 | 35 | - 用两个额外数组,分别记录每一位非c字符到左边第一个c的距离以及到右边第一个c的距离,然后取min即可。 36 | 37 | ```python 38 | class Solution: 39 | def shortestToChar(self, s: str, c: str) -> List[int]: 40 | cpos = [] # 记录c在s中的所有位置 41 | for i, ch in enumerate(s): 42 | if ch == c: 43 | cpos.append(i) 44 | left, right = [], [] 45 | i, j = 0, len(s) - 1 46 | for x in cpos: 47 | while x >= i: 48 | left.append(x - i) 49 | i += 1 50 | for x in cpos[::-1]: 51 | while x <= j: 52 | right.insert(0, j - x) 53 | j -= 1 54 | while j >= 0: 55 | right.insert(0, float('inf')) # 最大值表示到不可达 56 | j -= 1 57 | while i < len(s): 58 | left.append(float('inf')) 59 | i += 1 60 | 61 | res = [] 62 | for i in range(len(s)): 63 | res.append(min(left[i], right[i])) 64 | return res 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /每日一题/83. 删除有序链表中的重复元素.md: -------------------------------------------------------------------------------- 1 | ## 83. 删除有序链表中的重复元素 2 | 3 | https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ 4 | 5 | 存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。 6 | 7 | 返回同样按升序排列的结果链表。 8 | 9 | 10 | 11 | 示例 1: 12 | 13 | ![img](https://assets.leetcode.com/uploads/2021/01/04/list1.jpg) 14 | 15 | 输入:head = [1,1,2] 16 | 输出:[1,2] 17 | 示例 2: 18 | 19 | ![img](https://assets.leetcode.com/uploads/2021/01/04/list1.jpg) 20 | 21 | 输入:head = [1,1,2,3,3] 22 | 输出:[1,2,3] 23 | 24 | 25 | 提示: 26 | 27 | 链表中节点数目在范围 [0, 300] 内 28 | -100 <= Node.val <= 100 29 | 题目数据保证链表已经按升序排列 30 | 31 | ```java 32 | class Solution { 33 | public ListNode deleteDuplicates(ListNode head) { 34 | if (head == null || head.next == null) return head; 35 | ListNode p, q; 36 | p = head; q = head.next; 37 | while (p != null && q != null) { 38 | if (p.val == q.val) { 39 | p.next = q.next; 40 | q = p.next; 41 | } else p = p.next; 42 | } 43 | return head; 44 | } 45 | } 46 | ``` 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /每日一题/832. Flipping an Image.md: -------------------------------------------------------------------------------- 1 | ## 832. Flipping an Image 2 | 3 | https://leetcode.com/problems/flipping-an-image/ 4 | 5 | Given a binary matrix `A`, we want to flip the image horizontally, then invert it, and return the resulting image. 6 | 7 | To flip an image horizontally means that each row of the image is reversed. For example, flipping `[1, 1, 0]` horizontally results in `[0, 1, 1]`. 8 | 9 | To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. For example, inverting `[0, 1, 1]` results in `[1, 0, 0]`. 10 | 11 | ### 代码 12 | 13 | ```python 14 | class Solution(object): 15 | def flipAndInvertImage(self, A): 16 | """ 17 | :type A: List[List[int]] 18 | :rtype: List[List[int]] 19 | """ 20 | # flip 21 | if not A: return [] 22 | for i, img in enumerate(A): 23 | A[i] = img[::-1] 24 | 25 | # Invert 26 | for i, img in enumerate(A): 27 | for j, pixel in enumerate(img): 28 | if pixel == 0: 29 | img[j] = 1 30 | else: 31 | img[j] = 0 32 | return A 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /每日一题/841. Keys and Rooms.md: -------------------------------------------------------------------------------- 1 | ## 841. Keys and Rooms 2 | 3 | There are `N` rooms and you start in room `0`. Each room has a distinct number in `0, 1, 2, ..., N-1`, and each room may have some keys to access the next room. 4 | 5 | Formally, each room `i` has a list of keys `rooms[i]`, and each key `rooms[i][j]` is an integer in `[0, 1, ..., N-1]` where `N = rooms.length`. A key `rooms[i][j] = v` opens the room with number `v`. 6 | 7 | Initially, all the rooms start locked (except for room `0`). 8 | 9 | You can walk back and forth between rooms freely. 10 | 11 | Return `true` if and only if you can enter every room. 12 | 13 | 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: [[1],[2],[3],[]] 19 | Output: true 20 | Explanation: 21 | We start in room 0, and pick up key 1. 22 | We then go to room 1, and pick up key 2. 23 | We then go to room 2, and pick up key 3. 24 | We then go to room 3. Since we were able to go to every room, we return true. 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: [[1,3],[3,0,1],[2],[0]] 31 | Output: false 32 | Explanation: We can't enter the room with number 2. 33 | ``` 34 | 35 | **Note:** 36 | 37 | 1. `1 <= rooms.length <= 1000` 38 | 2. `0 <= rooms[i].length <= 1000` 39 | 3. The number of keys in all rooms combined is at most `3000`. 40 | 41 | ### 代码 42 | 43 | ```java 44 | class Solution { 45 | public boolean canVisitAllRooms(List> rooms) { 46 | Set visit = new HashSet<>(); 47 | dfs(rooms, 0, visit); 48 | return visit.size() == rooms.size(); 49 | } 50 | public void dfs(List> rooms, int cur, Set visit) { 51 | if (visit.contains(cur)) return; 52 | visit.add(cur); 53 | for (Integer r : rooms.get(cur)) 54 | dfs(rooms, r, visit); 55 | } 56 | } 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /每日一题/856. Score of Parentheses.md: -------------------------------------------------------------------------------- 1 | ## 856. Score of Parentheses 2 | 3 | https://leetcode.com/problems/score-of-parentheses/ 4 | 5 | Given a balanced parentheses string `S`, compute the score of the string based on the following rule: 6 | 7 | - `()` has score 1 8 | - `AB` has score `A + B`, where A and B are balanced parentheses strings. 9 | - `(A)` has score `2 * A`, where A is a balanced parentheses string. 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: "()" 17 | Output: 1 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: "(())" 24 | Output: 2 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: "()()" 31 | Output: 2 32 | ``` 33 | 34 | **Example 4:** 35 | 36 | ``` 37 | Input: "(()(()))" 38 | Output: 6 39 | ``` 40 | 41 | 42 | 43 | **Note:** 44 | 45 | 1. `S` is a balanced parentheses string, containing only `(` and `)`. 46 | 2. `2 <= S.length <= 50` 47 | 48 | ### 代码 49 | 50 | ```java 51 | class Solution { 52 | public int scoreOfParentheses(String _S) { 53 | int i = 0, n = _S.length(); 54 | int res = 0; 55 | char[] s = _S.toCharArray(); 56 | Deque stack = new ArrayDeque<>(); 57 | while (i < n) { 58 | if (s[i] == '(') { 59 | if (s[i + 1] == ')') { 60 | res ++; 61 | i ++; 62 | } 63 | else { 64 | stack.push(res); 65 | res = 0; 66 | } 67 | } 68 | else { 69 | res = stack.peek() + res * 2; 70 | stack.pop(); 71 | } 72 | i ++; 73 | } 74 | return res; 75 | } 76 | } 77 | ``` 78 | 79 | -------------------------------------------------------------------------------- /每日一题/86. Partition List.md: -------------------------------------------------------------------------------- 1 | ## 86. Partition List 2 | 3 | https://leetcode.com/problems/partition-list/ 4 | 5 | Given 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`. 6 | 7 | You should **preserve** the original relative order of the nodes in each of the two partitions. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ![img](https://assets.leetcode.com/uploads/2021/01/04/partition.jpg) 14 | 15 | ``` 16 | Input: head = [1,4,3,2,5,2], x = 3 17 | Output: [1,2,2,4,3,5] 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: head = [2,1], x = 2 24 | Output: [1,2] 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - The number of nodes in the list is in the range `[0, 200]`. 32 | - `-100 <= Node.val <= 100` 33 | - `-200 <= x <= 200` 34 | 35 | ### 代码 36 | 37 | ```java 38 | /** 39 | * Definition for singly-linked list. 40 | * public class ListNode { 41 | * int val; 42 | * ListNode next; 43 | * ListNode() {} 44 | * ListNode(int val) { this.val = val; } 45 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 46 | * } 47 | */ 48 | class Solution { 49 | public ListNode partition(ListNode head, int x) { 50 | ListNode dummy1 = new ListNode(0), dummy2 = new ListNode(0); 51 | ListNode p1 = dummy1, p2 = dummy2; 52 | while (head != null) { 53 | if (head.val < x) 54 | p1 = p1.next = head; 55 | else 56 | p2 = p2.next = head; 57 | head = head.next; 58 | } 59 | p2.next = null; 60 | p1.next = dummy2.next; 61 | return dummy1.next; 62 | } 63 | } 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /每日一题/88. Merge Sorted Array.md: -------------------------------------------------------------------------------- 1 | ## 88. Merge Sorted Array 2 | 3 | https://leetcode.com/problems/merge-sorted-array/ 4 | 5 | Given two sorted integer arrays `nums1` and `nums2`, merge `nums2` into `nums1` as one sorted array. 6 | 7 | The number of elements initialized in `nums1` and `nums2` are `m` and `n` respectively. You may assume that `nums1` has enough space (size that is equal to `m + n`) to hold additional elements from `nums2`. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 15 | Output: [1,2,2,3,5,6] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 22 | Output: [1] 23 | ``` 24 | 25 | 26 | 27 | **Constraints:** 28 | 29 | - `0 <= n, m <= 200` 30 | - `1 <= n + m <= 200` 31 | - `nums1.length == m + n` 32 | - `nums2.length == n` 33 | - `-109 <= nums1[i], nums2[i] <= 109` 34 | 35 | ### 代码 36 | 37 | ```java 38 | class Solution { 39 | public void merge(int[] nums1, int m, int[] nums2, int n) { 40 | int k = m + n - 1; 41 | int i = m - 1; 42 | int j = n - 1; 43 | while (i >= 0 && j >= 0) { 44 | if (nums1[i] >= nums2[j]) 45 | nums1[k--] = nums1[i--]; 46 | else 47 | nums1[k--] = nums2[j--]; 48 | } 49 | while (j >= 0) 50 | nums1[k--] = nums2[j--]; 51 | } 52 | } 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /每日一题/881. Boats to Save People.md: -------------------------------------------------------------------------------- 1 | ## 881. Boats to Save People 2 | 3 | https://leetcode.com/problems/boats-to-save-people/ 4 | 5 | The `i`-th person has weight `people[i]`, and each boat can carry a maximum weight of `limit`. 6 | 7 | Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most `limit`. 8 | 9 | Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.) 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: people = [1,2], limit = 3 17 | Output: 1 18 | Explanation: 1 boat (1, 2) 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: people = [3,2,2,1], limit = 3 25 | Output: 3 26 | Explanation: 3 boats (1, 2), (2) and (3) 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: people = [3,5,3,4], limit = 5 33 | Output: 4 34 | Explanation: 4 boats (3), (3), (4), (5) 35 | ``` 36 | 37 | **Note**: 38 | 39 | - `1 <= people.length <= 50000` 40 | - `1 <= people[i] <= limit <= 30000` 41 | 42 | ### 代码 43 | 44 | - 双指针 45 | 46 | ```python 47 | class Solution(object): 48 | def numRescueBoats(self, people, limit): 49 | """ 50 | :type people: List[int] 51 | :type limit: int 52 | :rtype: int 53 | """ 54 | people.sort(reverse = True) 55 | i, j = 0, len(people) - 1 56 | while i <= j: 57 | if people[i] + people[j] <= limit: 58 | j -= 1 59 | i += 1 60 | return i 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /每日一题/897. Increasing Order Search Tree.md: -------------------------------------------------------------------------------- 1 | ## 897. Increasing Order Search Tree 2 | 3 | https://leetcode.com/problems/increasing-order-search-tree/ 4 | 5 | Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ![img](https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg) 12 | 13 | ``` 14 | Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] 15 | Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ![img](https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg) 21 | 22 | ``` 23 | Input: root = [5,1,7] 24 | Output: [1,null,5,null,7] 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - The number of nodes in the given tree will be in the range `[1, 100]`. 32 | - `0 <= Node.val <= 1000` 33 | 34 | ### 代码 35 | 36 | ```python 37 | # Definition for a binary tree node. 38 | # class TreeNode(object): 39 | # def __init__(self, val=0, left=None, right=None): 40 | # self.val = val 41 | # self.left = left 42 | # self.right = right 43 | 44 | class Solution: 45 | def increasingBST(self, root): 46 | dummy = TreeNode(0) 47 | self.prev = dummy 48 | def inorder(root): 49 | if not root: return None 50 | inorder(root.left) 51 | root.left = None 52 | self.prev.right = root 53 | self.prev = root 54 | inorder(root.right) 55 | inorder(root) 56 | return dummy.right 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /每日一题/905. Sort Array By Parity.md: -------------------------------------------------------------------------------- 1 | ## 905. Sort Array By Parity 2 | 3 | https://leetcode.com/problems/sort-array-by-parity/ 4 | 5 | Given an array `A` of non-negative integers, return an array consisting of all the even elements of `A`, followed by all the odd elements of `A`. 6 | 7 | You may return any answer array that satisfies this condition. 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: [3,1,2,4] 15 | Output: [2,4,3,1] 16 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 17 | ``` 18 | 19 | ### 代码 20 | 21 | ```python 22 | class Solution: 23 | def sortArrayByParity(self, A: List[int]) -> List[int]: 24 | if not A: 25 | return A 26 | count = 0 27 | res = [] 28 | for i, num in enumerate(A): 29 | if num & 1 == 1: 30 | res.append(num) 31 | else: 32 | res.insert(0, num) 33 | return res 34 | ``` 35 | 36 | -------------------------------------------------------------------------------- /每日一题/91. Decode Ways.md: -------------------------------------------------------------------------------- 1 | ## 91. Decode Ways 2 | 3 | https://leetcode.com/problems/decode-ways/ 4 | 5 | A message containing letters from `A-Z` is being encoded to numbers using the following mapping: 6 | 7 | ``` 8 | 'A' -> 1 9 | 'B' -> 2 10 | ... 11 | 'Z' -> 26 12 | ``` 13 | 14 | Given a **non-empty** string containing only digits, determine the total number of ways to decode it. 15 | 16 | The answer is guaranteed to fit in a **32-bit** integer. 17 | 18 | 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: s = "12" 24 | Output: 2 25 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 26 | ``` 27 | 28 | **Example 2:** 29 | 30 | ``` 31 | Input: s = "226" 32 | Output: 3 33 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 34 | ``` 35 | 36 | **Example 3:** 37 | 38 | ``` 39 | Input: s = "0" 40 | Output: 0 41 | Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'. 42 | ``` 43 | 44 | **Example 4:** 45 | 46 | ``` 47 | Input: s = "1" 48 | Output: 1 49 | ``` 50 | 51 | 52 | 53 | **Constraints:** 54 | 55 | - `1 <= s.length <= 100` 56 | - `s` contains only digits and may contain leading zero(s). 57 | 58 | 59 | 60 | ### 代码 61 | 62 | - DP 思路 63 | 64 | ```python 65 | def solve(s): 66 | if not s or len(s) == 0: 67 | return 0 68 | n = len(s) 69 | dp = [0] * (1 + n) 70 | dp[0] = 1 71 | dp[1] = 1 if s[0] != '0' else 0 72 | for i in range(2, n + 1): 73 | if int(s[i-1]) != 0: 74 | dp[i] += dp[i-1] 75 | if 10 <= int(s[i-2:i]) <= 26: 76 | dp[i] += dp[i-2] 77 | return dp[n] 78 | ``` 79 | 80 | -------------------------------------------------------------------------------- /每日一题/910. Smallest Range II.md: -------------------------------------------------------------------------------- 1 | ## 910. Smallest Range II 2 | 3 | https://leetcode.com/problems/smallest-range-ii/solution/ 4 | 5 | Given an array `A` of integers, for each integer `A[i]` we need to choose **either `x = -K` or `x = K`**, and add `x` to `A[i] **(only once)**`. 6 | 7 | After this process, we have some array `B`. 8 | 9 | Return the smallest possible difference between the maximum value of `B` and the minimum value of `B`. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: A = [1], K = 0 15 | Output: 0 16 | Explanation: B = [1] 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: A = [0,10], K = 2 23 | Output: 6 24 | Explanation: B = [2,8] 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: A = [1,3,6], K = 3 31 | Output: 3 32 | Explanation: B = [4,6,3] 33 | ``` 34 | 35 | ### 代码 36 | 37 | ```python 38 | class Solution(object): 39 | def smallestRangeII(self, A, K): 40 | n = len(A) 41 | A.sort() 42 | res = A[n-1] - A[0] 43 | minVal, maxVal = A[0], A[n - 1] 44 | 45 | for i in range(n-1): 46 | a, b = A[i], A[i+1] 47 | high, low = max(a+K, maxVal-K), min(minVal+K, b-K) 48 | res = min(res, high - low) 49 | 50 | return res 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /每日一题/915. Partition Array into Disjoint Intervals.md: -------------------------------------------------------------------------------- 1 | ## 915. Partition Array into Disjoint Intervals 2 | 3 | https://leetcode.com/problems/partition-array-into-disjoint-intervals/ 4 | 5 | Given an array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: 6 | 7 | - Every element in `left` is less than or equal to every element in `right`. 8 | - `left` and `right` are non-empty. 9 | - `left` has the smallest possible size. 10 | 11 | Return the **length** of `left` after such a partitioning. It is guaranteed that such a partitioning exists. 12 | 13 | 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: nums = [5,0,3,8,6] 19 | Output: 3 20 | Explanation: left = [5,0,3], right = [8,6] 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: nums = [1,1,1,0,6,12] 27 | Output: 4 28 | Explanation: left = [1,1,1,0], right = [6,12] 29 | ``` 30 | 31 | 32 | 33 | **Note:** 34 | 35 | 1. `2 <= nums.length <= 30000` 36 | 2. `0 <= nums[i] <= 106` 37 | 3. It is guaranteed there is at least one way to partition `nums` as described. 38 | 39 | 40 | 41 | ### 代码 42 | 43 | ```java 44 | class Solution { 45 | public int partitionDisjoint(int[] nums) { 46 | int n = nums.length; 47 | int curMax = nums[0], idx = 0, max = curMax; 48 | for (int i = 1; i < nums.length; i++) { 49 | if (nums[i] < curMax) { 50 | curMax = max; 51 | idx = i; 52 | } else max = Math.max(max, nums[i]); 53 | } 54 | return idx + 1; 55 | } 56 | } 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /每日一题/92. Reverse Linked List II.md: -------------------------------------------------------------------------------- 1 | ## 92. Reverse Linked List II 2 | 3 | Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return *the reversed list*. 4 | 5 | 6 | 7 | **Example 1:** 8 | 9 | ![img](https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg) 10 | 11 | ``` 12 | Input: head = [1,2,3,4,5], left = 2, right = 4 13 | Output: [1,4,3,2,5] 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: head = [5], left = 1, right = 1 20 | Output: [5] 21 | ``` 22 | 23 | 24 | 25 | **Constraints:** 26 | 27 | - The number of nodes in the list is `n`. 28 | - `1 <= n <= 500` 29 | - `-500 <= Node.val <= 500` 30 | - `1 <= left <= right <= n` 31 | 32 | 33 | 34 | ### 代码 35 | 36 | ```java 37 | /** 38 | * Definition for singly-linked list. 39 | * public class ListNode { 40 | * int val; 41 | * ListNode next; 42 | * ListNode() {} 43 | * ListNode(int val) { this.val = val; } 44 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 45 | * } 46 | */ 47 | class Solution { 48 | public ListNode reverseBetween(ListNode head, int a, int b) { 49 | if (head == null) return null; 50 | int gap = b - a; 51 | ListNode dummy = new ListNode(-1); 52 | dummy.next = head; 53 | ListNode cur = dummy, pre = dummy; 54 | 55 | while (a-- > 0) { 56 | pre = cur; 57 | cur = cur.next; 58 | } 59 | 60 | while (gap-- > 0) { 61 | ListNode next = cur.next; 62 | cur.next = next.next; 63 | next.next = pre.next; 64 | pre.next = next; 65 | } 66 | return dummy.next; 67 | } 68 | } 69 | ``` 70 | 71 | -------------------------------------------------------------------------------- /每日一题/938. Range Sum of BST.md: -------------------------------------------------------------------------------- 1 | ## 938. Range Sum of BST 2 | 3 | https://leetcode.com/problems/range-sum-of-bst/ 4 | 5 | Given the `root` node of a binary search tree, return *the sum of values of all nodes with a value in the range `[low, high]`*. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ![img](https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg) 12 | 13 | ``` 14 | Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 15 | Output: 32 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ![img](https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg) 21 | 22 | ``` 23 | Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 24 | Output: 23 25 | ``` 26 | 27 | 28 | 29 | **Constraints:** 30 | 31 | - The number of nodes in the tree is in the range `[1, 2 * 104]`. 32 | - `1 <= Node.val <= 105` 33 | - `1 <= low <= high <= 105` 34 | - All `Node.val` are **unique**. 35 | 36 | ### 代码 37 | 38 | ```python 39 | class Solution(object): 40 | def rangeSumBST(self, root, L, R): 41 | """ 42 | :type root: TreeNode 43 | :type L: int 44 | :type R: int 45 | :rtype: int 46 | """ 47 | def dfs(node): 48 | if node: 49 | if L <= node.val <= R: 50 | self.ans += node.val 51 | if L < node.val: 52 | dfs(node.left) 53 | if node.val < R: 54 | dfs(node.right) 55 | 56 | self.ans = 0 57 | dfs(root) 58 | return self.ans 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /每日一题/967. Numbers With Same Consecutive Differences.md: -------------------------------------------------------------------------------- 1 | ## 967. Numbers With Same Consecutive Differences 2 | 3 | https://leetcode.com/problems/numbers-with-same-consecutive-differences/ 4 | 5 | Return all **non-negative** integers of length `N` such that the absolute difference between every two consecutive digits is `K`. 6 | 7 | Note that **every** number in the answer **must not** have leading zeros **except** for the number `0` itself. For example, `01` has one leading zero and is invalid, but `0` is valid. 8 | 9 | You may return the answer in any order. 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: N = 3, K = 7 15 | Output: [181,292,707,818,929] 16 | Explanation: Note that 070 is not a valid number, because it has leading zeroes. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: N = 2, K = 1 23 | Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98] 24 | ``` 25 | 26 | ### 思路 27 | 28 | - DFS,时间复杂度为O(N) 29 | - DFS参数,N:剩余位数,K:差值,temp:当前构成的数字(current number) 30 | 31 | ### 代码 32 | 33 | ```python 34 | class Solution: 35 | def numsSameConsecDiff(self, N: int, K: int) -> List[int]: 36 | 37 | res = [] 38 | if N == 1: 39 | res.append(0) 40 | for i in range(1, 10): 41 | self.dfs(res, N-1, K, i) 42 | return res 43 | 44 | def dfs(self, res, N, K, temp): 45 | if N == 0: 46 | res.append(temp) 47 | return 48 | 49 | last_digit = temp % 10 50 | if last_digit + K <= 9: 51 | self.dfs(res, N-1, K, temp * 10 + last_digit + K) 52 | if last_digit - K >= 0 and K != 0: 53 | self.dfs(res, N-1, K, temp * 10 + last_digit - K) 54 | 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /每日一题/97. Interleaving String (hard).md: -------------------------------------------------------------------------------- 1 | ## 97. Interleaving String (hard) 2 | 3 | https://leetcode.com/problems/interleaving-string/ 4 | 5 | Given `s1`, `s2`, and `s3`, find whether `s3` is formed by the interleaving of `s1` and `s2`. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ![img](https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg) 12 | 13 | ``` 14 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" 15 | Output: true 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" 22 | Output: false 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: s1 = "", s2 = "", s3 = "" 29 | Output: true 30 | ``` 31 | 32 | 33 | 34 | **Constraints:** 35 | 36 | - `0 <= s1.length, s2.length <= 100` 37 | - `0 <= s3.length <= 200` 38 | - `s1`, `s2`, and `s3` consist of lower-case English letters. 39 | 40 | 41 | 42 | ### 代码 43 | 44 | ```python 45 | class Solution: 46 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 47 | if len(s3) != len(s1) + len(s2): return False 48 | m, n = len(s1), len(s2) 49 | dp = [[True for _ in range(n+1)] for _ in range(m+1)] 50 | for i in range(m+1): 51 | for j in range(n+1): 52 | if i==0 and j==0: dp[i][j] = True 53 | elif i == 0: 54 | # first row 55 | dp[i][j] = dp[i][j-1] and s2[j-1] == s3[i+j-1] 56 | elif j == 0: 57 | # first col 58 | dp[i][j] = dp[i-1][j] and s1[i-1] == s3[i+j-1] 59 | else: 60 | dp[i][j] = (dp[i][j-1] and s2[j-1] == s3[i+j-1]) or (dp[i-1][j] and s1[i-1] == s3[i+j-1]) 61 | 62 | return dp[m][n] 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /每日一题/974. Subarray Sums Divisible by K.md: -------------------------------------------------------------------------------- 1 | ## 974. Subarray Sums Divisible by K 2 | 3 | https://leetcode.com/problems/subarray-sums-divisible-by-k/ 4 | 5 | Given an array `A` of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by `K`. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: A = [4,5,0,-2,-3,1], K = 5 11 | Output: 7 12 | Explanation: There are 7 subarrays with a sum divisible by K = 5: 13 | [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] 14 | ``` 15 | 16 | **Note:** 17 | 18 | 1. `1 <= A.length <= 30000` 19 | 2. `-10000 <= A[i] <= 10000` 20 | 3. `2 <= K <= 10000` 21 | 22 | ### 代码 23 | 24 | Python 25 | 26 | ```python 27 | class Solution: 28 | def subarraysDivByK(self, A: List[int], K: int) -> int: 29 | dic = defaultdict(int) 30 | dic[0] = 1 31 | res, prefix_sum = 0, 0 32 | for x in A: 33 | prefix_sum = (prefix_sum + x) % K 34 | dic[prefix_sum] += 1 35 | res += dic[prefix_sum] - 1 36 | return res 37 | ``` 38 | 39 | Java 40 | 41 | ```Java 42 | class Solution { 43 | public int subarraysDivByK(int[] A, int K) { 44 | HashMap map = new HashMap<>(); 45 | int ans = 0, prefixSum = 0; 46 | map.put(0, 1); 47 | for (int x : A) { 48 | prefixSum += x; 49 | prefixSum %= K; 50 | if (prefixSum < 0) 51 | // 余数为负数的情况 52 | prefixSum += K; 53 | 54 | map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1); 55 | ans += map.get(prefixSum) - 1; 56 | } 57 | return ans; 58 | } 59 | } 60 | ``` 61 | 62 | -------------------------------------------------------------------------------- /每日一题/991. Broken Calculator.md: -------------------------------------------------------------------------------- 1 | ## 991. Broken Calculator 2 | 3 | https://leetcode.com/problems/broken-calculator/ 4 | 5 | On a broken calculator that has a number showing on its display, we can perform two operations: 6 | 7 | - **Double**: Multiply the number on the display by 2, or; 8 | - **Decrement**: Subtract 1 from the number on the display. 9 | 10 | Initially, the calculator is displaying the number `X`. 11 | 12 | Return the minimum number of operations needed to display the number `Y`. 13 | 14 | 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: X = 2, Y = 3 20 | Output: 2 21 | Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: X = 5, Y = 8 28 | Output: 2 29 | Explanation: Use decrement and then double {5 -> 4 -> 8}. 30 | ``` 31 | 32 | **Example 3:** 33 | 34 | ``` 35 | Input: X = 3, Y = 10 36 | Output: 3 37 | Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}. 38 | ``` 39 | 40 | **Example 4:** 41 | 42 | ``` 43 | Input: X = 1024, Y = 1 44 | Output: 1023 45 | Explanation: Use decrement operations 1023 times. 46 | ``` 47 | 48 | 49 | 50 | **Note:** 51 | 52 | 1. `1 <= X <= 10^9` 53 | 2. `1 <= Y <= 10^9` 54 | 55 | ### 代码 56 | 57 | ```java 58 | class Solution { 59 | public int brokenCalc(int X, int Y) { 60 | int res = 0; 61 | while (Y > X) { 62 | Y = Y % 2 > 0 ? Y + 1 : Y / 2; 63 | res++; 64 | } 65 | return res + X - Y; 66 | } 67 | } 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /每日一题/Acwing 1455. 招聘.md: -------------------------------------------------------------------------------- 1 | ### Acwing 1455. 招聘 2 | 3 | 题目链接:https://www.acwing.com/problem/content/1457/;参考约瑟夫环问题。 4 | 5 | #### 代码 6 | 7 | ```java 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | 12 | public class Main { 13 | public static int[] A = new int[1010]; 14 | 15 | public static void main(String[] args) throws IOException{ 16 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 17 | int T = Integer.parseInt(bf.readLine()); 18 | while (T -- > 0) { 19 | // input n, m, A1, A2,..., Am 20 | String[] S = bf.readLine().split(" "); 21 | int n = Integer.parseInt(S[0]), m = Integer.parseInt(S[1]); 22 | for (int i = 0; i < m; i++ ) { 23 | A[i] = Integer.parseInt(S[i+2]); 24 | } 25 | int res = 0; 26 | for (int i = 1, j = (n - 1) % m; i < n;) { 27 | i++; 28 | j = (j + m - 1) % m; 29 | res = (res + A[j]) % i; 30 | } 31 | System.out.println(res); 32 | } 33 | } 34 | } 35 | ``` 36 | 37 | -------------------------------------------------------------------------------- /每日一题/BinarySearch.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | /** 3 | * 使用递归的二分查找 4 | *title:recursionBinarySearch 5 | *@param arr 有序数组 6 | *@param key 待查找关键字 7 | *@return 找到的位置 8 | */ 9 | public static int recursionBinarySearch(int[] arr,int key,int low,int high){ 10 | 11 | if(key < arr[low] || key > arr[high] || low > high){ 12 | return -1; 13 | } 14 | 15 | int middle = (low + high) / 2; //初始中间位置 16 | if(arr[middle] > key){ 17 | //比关键字大则关键字在左区域 18 | return recursionBinarySearch(arr, key, low, middle - 1); 19 | }else if(arr[middle] < key){ 20 | //比关键字小则关键字在右区域 21 | return recursionBinarySearch(arr, key, middle + 1, high); 22 | }else { 23 | return middle; 24 | } 25 | 26 | } 27 | 28 | /** 29 | * 不使用递归的二分查找 30 | *title:commonBinarySearch 31 | *@param arr 32 | *@param key 33 | *@return 关键字位置 34 | */ 35 | public static int commonBinarySearch(int[] arr,int key){ 36 | int low = 0; 37 | int high = arr.length - 1; 38 | int middle = 0; //定义middle 39 | 40 | if(key < arr[low] || key > arr[high] || low > high){ 41 | return -1; 42 | } 43 | 44 | while(low <= high){ 45 | middle = (low + high) / 2; 46 | if(arr[middle] > key){ 47 | //比关键字大则关键字在左区域 48 | high = middle - 1; 49 | }else if(arr[middle] < key){ 50 | //比关键字小则关键字在右区域 51 | low = middle + 1; 52 | }else{ 53 | return middle; 54 | } 55 | } 56 | 57 | return -1; //最后仍然没有找到,则返回-1 58 | } 59 | 60 | public static void main(String[] args) { 61 | int[] arr = {1,3,5,7,9,11}; 62 | int key = 4; 63 | //int position = recursionBinarySearch(arr,key,0,arr.length - 1); 64 | 65 | int position = commonBinarySearch(arr, key); 66 | 67 | if(position == -1){ 68 | System.out.println("查找的是"+key+",序列中没有该数!"); 69 | }else{ 70 | System.out.println("查找的是"+key+",找到位置为:"+position); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /每日一题/src/1413.java: -------------------------------------------------------------------------------- 1 | /* 2 | Input: nums = [-3,2,-3,4,2] 3 | Output: 5 4 | Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1. 5 | step by step sum 6 | startValue = 4 | startValue = 5 | nums 7 | (4 -3 ) = 1 | (5 -3 ) = 2 | -3 8 | (1 +2 ) = 3 | (2 +2 ) = 4 | 2 9 | (3 -3 ) = 0 | (4 -3 ) = 1 | -3 10 | (0 +4 ) = 4 | (1 +4 ) = 5 | 4 11 | (4 +2 ) = 6 | (5 +2 ) = 7 | 2 12 | */ 13 | 14 | class Solution { 15 | public int minStartValue(int[] nums) { 16 | int totalMin = Integer.MAX_VALUE; 17 | int sum = 0; 18 | for (int i = 0; i < nums.length; i++) { 19 | sum += nums[i]; 20 | totalMin = Math.min(totalMin, sum); 21 | } 22 | return totalMin <= 0 ? 1 - totalMin : 1; 23 | } 24 | } -------------------------------------------------------------------------------- /每日一题/src/495.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPoisonedDuration(int[] timeSeries, int duration) { 3 | int res = 0; 4 | if (timeSeries.length == 1) return duration; 5 | for (int i = 0; i < timeSeries.length - 1; i++) { 6 | if (timeSeries[i + 1] - timeSeries[i] >= duration) 7 | res += duration; 8 | else { 9 | res += timeSeries[i + 1] - timeSeries[i]; 10 | } 11 | } 12 | res += duration; 13 | return res; 14 | } 15 | } -------------------------------------------------------------------------------- /每日一题/template.md: -------------------------------------------------------------------------------- 1 | # 2 | 3 | ## 题目 4 | 5 | ## 思路 6 | 7 | ## 代码 8 | 9 | -------------------------------------------------------------------------------- /每日一题/【Day 02】 2020-06-02 - 75. 颜色分类.md: -------------------------------------------------------------------------------- 1 | # 【Day 2】 2020-06-02 - 75. 颜色分类 2 | 3 | ### 题目 4 | 5 | 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 6 | 7 | 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 8 | 9 | 注意: 10 | 不能使用代码库中的排序函数来解决这道题。 11 | 12 | 示例: 13 | 14 | 输入: [2,0,2,1,1,0] 15 | 16 | 输出: [0,0,1,1,2,2] 17 | 18 | 进阶: 19 | 20 | 一个直观的解决方案是使用计数排序的两趟扫描算法。 21 | 22 | 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 23 | 24 | 你能想出一个仅使用常数空间的**一趟扫描**算法吗? 25 | 26 | 来源:力扣(LeetCode) 27 | 28 | 链接:https://leetcode-cn.com/problems/sort-colors 29 | 30 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 31 | 32 | ### 思路 33 | 34 | 用三个指针即可。分别是low, high, i 35 | 36 | - 遇到颜色1,让游标 i 直接跳过,不管 37 | - 遇到颜色2,让当前数 nums[i] 与 nums[high]交换,交换后high --,i 不动 38 | - 遇到颜色3,让当前数 nums[i] 与 nums[low] 交换,交换后同时往后移动 i 和 low。 39 | 40 | ### 代码 41 | 42 | ```python 43 | class Solution: 44 | def sortColors(self, nums: List[int]) -> None: 45 | """ 46 | Do not return anything, modify nums in-place instead. 47 | """ 48 | lo, hi = 0, len(nums)-1 49 | i = 0 50 | 51 | while i <= hi: 52 | if nums[i] == 0: 53 | nums[i], nums[lo] = nums[lo], nums[i] 54 | i += 1 55 | lo += 1 56 | elif nums[i] == 2: 57 | nums[i], nums[hi] = nums[hi], nums[i] 58 | hi -= 1 59 | else: 60 | i += 1 61 | ``` -------------------------------------------------------------------------------- /每日一题/【Day 07】 2020-06-07 - 206. 反转链表.md: -------------------------------------------------------------------------------- 1 | # 【Day 7】 2020-06-07 - 206. 反转链表 2 | 3 | ### 题目 4 | 5 | 反转一个单链表。 6 | 7 | 示例: 8 | 9 | 输入: 1->2->3->4->5->NULL 10 | 11 | 输出: 5->4->3->2->1->NULL 12 | 13 | 进阶: 14 | 15 | 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 16 | 17 | 来源:力扣(LeetCode) 18 | 19 | 链接:https://leetcode-cn.com/problems/reverse-linked-list 20 | 21 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 22 | 23 | 24 | ### Iteration 思路 25 | 26 | - 设置三个指针,prev ,curr,next 27 | 28 | - prev = null , curr = head, next = head.next 29 | 30 | - 当 curr 不为空时,就让 next 的指针转向,比如1->2->3,我们需要让2掉头指向1。 31 | - 最后,依次让 prev, curr, next 后移。最终返回 prev。 32 | 33 | ```python 34 | # Definition for singly-linked list. 35 | # class ListNode: 36 | # def __init__(self, x): 37 | # self.val = x 38 | # self.next = None 39 | 40 | class Solution: 41 | def reverseList(self, head: ListNode) -> ListNode: 42 | curr = head 43 | prev = None 44 | 45 | while curr != None: 46 | next = curr.next 47 | curr.next = prev 48 | prev = curr 49 | curr = next 50 | 51 | return prev 52 | ``` 53 | 54 | ### Recursion 递归思路 55 | 56 | - 先反转后面的链表,从最后面的两个结点开始反转,依次向前,将后一个链表结点指向前一个结点,注意每次反转后要将原链表中前一个结点的指针域置 null ,表示将原链表中前一个结点指向后一个结点的指向关系断开。 57 | 58 | ```python 59 | # recurision 60 | 61 | class Solution: 62 | def reverseList(self, head: ListNode) -> ListNode: 63 | if head == None or head.next == None: 64 | return head 65 | else: 66 | new_head = self.reverseList(head.next) # 找到链表最后一个不为空的节点 67 | head.next.next = head 68 | head.next = None # 断开前一个节点指向后一个节点的关系 69 | 70 | return new_head 71 | ``` -------------------------------------------------------------------------------- /每日一题/【Day 09】 2020-06-09 - 109. 有序链表转换二叉搜索树.md: -------------------------------------------------------------------------------- 1 | # 【Day 9】 2020-06-09 - 109. 有序链表转换二叉搜索树 2 | 3 | ### 题目 4 | 5 | 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 6 | 7 | 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 8 | 9 | 示例: 10 | 11 | 给定的有序链表: [-10, -3, 0, 5, 9], 12 | 13 | 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 14 | 15 | ``` 16 | 0 17 | / \ 18 | -3 9 19 | / / 20 | -10 5 21 | ``` 22 | 23 | 来源:力扣(LeetCode) 24 | 25 | 链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree 26 | 27 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 28 | 29 | ### 思路 30 | 31 | - 这道题关键要找到链表的中点位置,然后将中点位置的node作为根节点,进行左右递归。 32 | - 利用快慢指针来找中点,fast 每次移动两步,slow 每次移动一步,当 fast 不再移动时,slow 的位置即为中点。 **参考**[快慢指针](https://juejin.im/post/5b46a7c75188251a8d36d482) 33 | - 找到中点后,要以中点的值建立一个数的根节点,然后需要把原链表断开,分为前后两个链表,都不能包含原中节点,然后再分别对这两个链表递归调用原函数,分别连上左右子节点即可。 34 | 35 | ### 代码 36 | 37 | ```java 38 | class Solution { 39 | public TreeNode sortedListToBST(ListNode head) { 40 | if (head == null) 41 | return null; 42 | if (head.next == null) 43 | return new TreeNode(head.val); 44 | ListNode slow = new ListNode(); 45 | ListNode fast = new ListNode(); 46 | ListNode last = new ListNode(); 47 | slow = head; 48 | fast = head; 49 | last = slow; 50 | while (fast.next != null && fast.next.next != null) { 51 | last = slow; 52 | slow = slow.next; 53 | fast = fast.next.next; 54 | } 55 | fast = slow.next; 56 | last.next = null; // 断开链表中点(last.next)位置 57 | TreeNode root = new TreeNode(slow.val); 58 | if (head != slow){ 59 | root.left = sortedListToBST(head); 60 | } 61 | root.right = sortedListToBST(fast); 62 | 63 | return root; 64 | } 65 | } 66 | ``` 67 | 68 | -------------------------------------------------------------------------------- /每日一题/【Day 10】 2020-06-10 - 160. 相交链表.md: -------------------------------------------------------------------------------- 1 | # 【Day 10】 2020-06-10 - 160. 相交链表 2 | 3 | 详见仓库内我的题解:[link](https://github.com/LLancelot/LeetCode/blob/master/LeetCode-Note.md#160-intersection-of-two-linked-lists) -------------------------------------------------------------------------------- /每日一题/【Day 12】- 146. LRU缓存机制.md: -------------------------------------------------------------------------------- 1 | # 【Day 12】- 146. LRU缓存机制 2 | 3 | ### 题目 4 | 5 | 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 6 | 7 | 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。 8 | 9 | 写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。 10 | 11 | **进阶:** 12 | 13 | 你是否可以在 O(1) 时间复杂度内完成这两种操作? 14 | 15 | 示例: 16 | 17 | ``` 18 | LRUCache cache = new LRUCache( 2 /* 缓存容量 */ ); 19 | 20 | cache.put(1, 1); 21 | cache.put(2, 2); 22 | cache.get(1); // 返回 1 23 | cache.put(3, 3); // 该操作会使得关键字 2 作废 24 | cache.get(2); // 返回 -1 (未找到) 25 | cache.put(4, 4); // 该操作会使得关键字 1 作废 26 | cache.get(1); // 返回 -1 (未找到) 27 | cache.get(3); // 返回 3 28 | cache.get(4); // 返回 4 29 | ``` 30 | 31 | 来源:力扣(LeetCode) 32 | 33 | 链接:https://leetcode-cn.com/problems/lru-cache 34 | 35 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 36 | 37 | -------------------------------------------------------------------------------- /每日一题/【Day 13】- 104. 二叉树的最大深度.md: -------------------------------------------------------------------------------- 1 | # 【Day 13 - 104. 二叉树的最大深度】 2 | 3 | ### 题目 4 | 5 | 给定一个二叉树,找出其最大深度。 6 | 7 | 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 8 | 9 | 说明: 叶子节点是指没有子节点的节点。 10 | 11 | 示例: 12 | 13 | 给定二叉树 [3,9,20,null,null,15,7], 14 | 15 | ``` 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | ``` 22 | 23 | 返回它的最大深度 3 。 24 | 25 | 来源:力扣(LeetCode) 26 | 27 | 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree 28 | 29 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 30 | 31 | ### 代码 32 | 33 | ```java 34 | class Solution { 35 | public int maxDepth(TreeNode root) { 36 | if (root == null) 37 | return 0; 38 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 39 | } 40 | } 41 | ``` 42 | 43 | -------------------------------------------------------------------------------- /每日一题/【Day 14】- 100. 相同的树.md: -------------------------------------------------------------------------------- 1 | # 【Day 14 - 100. 相同的树】 2 | 3 | 仓库链接:[link](https://github.com/LLancelot/LeetCode/blob/ce23c7b2b1ceafd91c2a82735d8c863e188dce7f/LeetCode-Note.md#100-same-tree-easy) -------------------------------------------------------------------------------- /每日一题/【Day 16】- 513. 找树左下角的值.md: -------------------------------------------------------------------------------- 1 | # 【Day 16 - 513. 找树左下角的值】 2 | 3 | 给定一个二叉树,在树的最后一行找到最左边的值。 4 | 5 | 示例 1: 6 | 7 | ``` 8 | 输入: 9 | 10 | 2 11 | / \ 12 | 1 3 13 | 14 | 输出: 15 | 1 16 | ``` 17 | 18 | 示例 2: 19 | 20 | ``` 21 | 输入: 22 | 23 | 1 24 | / \ 25 | 2 3 26 | / / \ 27 | 4 5 6 28 | / 29 | 7 30 | 31 | 输出: 32 | 7 33 | ``` 34 | 35 | 注意: 您可以假设树(即给定的根节点)不为 NULL。 36 | 37 | 来源:力扣(LeetCode) 38 | 39 | 链接:https://leetcode-cn.com/problems/find-bottom-left-tree-value 40 | 41 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 42 | 43 | ### 思路: 44 | 45 | - **层序遍历**二叉树,把每层的结果放到 res 中,遍历完成后直接返回最后一层的第一个元素```res[-1][0]``` 46 | 47 | ### 代码: 48 | 49 | ```python 50 | class Solution(object): 51 | def findBottomLeftValue(self, root): 52 | """ 53 | :type root: TreeNode 54 | :rtype: int 55 | """ 56 | res, queue = [], [] 57 | queue.append(root) 58 | while len(queue) != 0: 59 | temp = [] 60 | qsize = len(queue) 61 | for i in range(qsize): 62 | node = queue.pop(0) 63 | if node.left is not None: 64 | queue.append(node.left) 65 | if node.right is not None: 66 | queue.append(node.right) 67 | temp.append(node.val) 68 | res.append(temp) 69 | 70 | return res[-1][0] 71 | 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /每日一题/【Day 17】- 105. 从前序与中序遍历序列构造二叉树.md: -------------------------------------------------------------------------------- 1 | # 【Day 17】- 105. 从前序与中序遍历序列构造二叉树 2 | 3 | 仓库链接:[105. Construct Binary Tree from Preorder and Inorder Traversal](https://github.com/LLancelot/LeetCode/blob/master/LeetCode-Note.md#105-construct-binary-tree-from-preorder-and-inorder-traversal) 4 | 5 | -------------------------------------------------------------------------------- /每日一题/【Day 18】 - 124. 二叉树中的最大路径和.md: -------------------------------------------------------------------------------- 1 | # 【Day 18】 - 124. 二叉树中的最大路径和 2 | 3 | 仓库链接:[link](https://github.com/LLancelot/LeetCode/blob/ce23c7b2b1ceafd91c2a82735d8c863e188dce7f/LeetCode-Note.md#124-binary-tree-maximum-path-sum) -------------------------------------------------------------------------------- /每日一题/【Day19】- 1. 两数之和.md: -------------------------------------------------------------------------------- 1 | # 【Day19 - 1. 两数之和】 2 | 3 | -------------------------------------------------------------------------------- /每日一题/【Day20】 - 447. 回旋镖的数量.md: -------------------------------------------------------------------------------- 1 | # 【Day20 - 447. 回旋镖的数量】 2 | 3 | #### 题目 4 | 5 | 给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。 6 | 7 | 找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。 8 | 9 | 示例: 10 | 11 | 输入: 12 | 13 | [[0,0],[1,0],[2,0]] 14 | 15 | 输出: 16 | 17 | 2 18 | 19 | 解释: 20 | 21 | 两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]] 22 | 23 | 来源:力扣(LeetCode) 24 | 25 | 链接:https://leetcode-cn.com/problems/number-of-boomerangs 26 | 27 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 -------------------------------------------------------------------------------- /每日一题/【Day21】- 36. 有效的数独.md: -------------------------------------------------------------------------------- 1 | # 【Day21 - 36. 有效的数独】 -------------------------------------------------------------------------------- /每日一题/【Day22】- 645. 错误的集合.md: -------------------------------------------------------------------------------- 1 | # 【Day22 - 645. 错误的集合】 2 | 3 | #### 题目 4 | 5 | 集合 S 包含从1到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个元素复制了成了集合里面的另外一个元素的值,导致集合丢失了一个整数并且有一个元素重复。 6 | 7 | 给定一个数组 nums 代表了集合 S 发生错误后的结果。你的任务是首先寻找到重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。 8 | 9 | 示例 1: 10 | 11 | 输入: nums = [1,2,2,4] 12 | 13 | 输出: [2,3] 14 | 15 | 注意: 16 | 17 | 给定数组的长度范围是 [2, 10000]。 18 | 19 | 给定的数组是无序的。 20 | 21 | 来源:力扣(LeetCode) 22 | 23 | 链接:https://leetcode-cn.com/problems/set-mismatch 24 | 25 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 26 | 27 | -------------------------------------------------------------------------------- /每日一题/【Day23】- 面试题04.01. 节点间通路.md: -------------------------------------------------------------------------------- 1 | # 【Day23】- 面试题04.01. 节点间通路 2 | 3 | 节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。 4 | 5 | 示例1: 6 | 7 | 输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2 8 | 9 | 输出:true 10 | 11 | 示例2: 12 | 13 | 输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4 14 | 15 | 输出 true 16 | 17 | 提示: 18 | 19 | 节点数量n在[0, 1e5]范围内。 20 | 21 | 节点编号大于等于 0 小于 n。 22 | 23 | 图中可能存在自环和平行边。 24 | 25 | 来源:力扣(LeetCode) 26 | 27 | 链接:https://leetcode-cn.com/problems/route-between-nodes-lcci 28 | 29 | 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 30 | 31 | -------------------------------------------------------------------------------- /算法模板代码/acw_Java.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | public class Main { 6 | public static int[] q; 7 | 8 | public static void main(String[] args) throws IOException{ 9 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 10 | String[] ip1 = bf.readLine().split(" "); 11 | int N = Integer.parseInt(ip1[0]); 12 | String[] ip2 = bf.readLine().split(" "); 13 | 14 | } 15 | } -------------------------------------------------------------------------------- /算法模板代码/单链表.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | 4 | public class Main { 5 | public static int head, idx; 6 | public static int[] e, ne; 7 | public static void init() { 8 | head = -1; // head 9 | idx = 0; // bian hao 10 | } 11 | public static void add(int k, int x) { 12 | e[idx] = x; 13 | ne[idx] = ne[k]; 14 | ne[k] = idx++; 15 | } 16 | public static void addToHead(int x) { 17 | e[idx] = x; 18 | ne[idx] = head; 19 | head = idx++; 20 | } 21 | public static void remove(int k, int x) { 22 | ne[k] = ne[ne[k]]; 23 | } 24 | 25 | public static void main(String[] args) throws Exception { 26 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 27 | int n = Integer.parseInt(reader.readLine()); 28 | init(); 29 | while (n -- > 0) { 30 | // "H", add x to head; 31 | // "D", remove pos == k; 32 | // "I", insert x after pos == k; 33 | String[] input = reader.readLine().split(" "); 34 | if (input[0].equals("H")) addToHead(Integer.parseInt(input[1])); 35 | else if (input[0].equals("D")) { 36 | // if remove the head 37 | if (input[1].equals("0")) 38 | head = ne[head]; 39 | else remove(Integer.parseInt(input[1]) - 1); // 记得-1 40 | } 41 | else { 42 | // insert 43 | int pos = Integer.parseInt(input[1]), x = Integer.parseInt(input[2]); 44 | add(pos - 1, x); // 记得-1 45 | } 46 | } 47 | for (int i = head; i != -1; i = ne[i]) System.out.printf("%d ", e[i]); 48 | } 49 | } -------------------------------------------------------------------------------- /算法模板代码/字符串哈希.java: -------------------------------------------------------------------------------- 1 | // 作者:acw_林少 2 | // 链接:https://www.acwing.com/activity/content/code/content/994452/ 3 | // 来源:AcWing 4 | // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | 10 | public class Main { 11 | public static long[] h, p; 12 | public static int P = 131; 13 | 14 | public static long query(int l, int r) { 15 | return h[r] - h[l - 1] * p[r - l + 1]; 16 | } 17 | 18 | public static void main(String[] args) throws IOException{ 19 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 20 | String[] ip1 = bf.readLine().split(" "); 21 | String str = bf.readLine(); 22 | int n = Integer.parseInt(ip1[0]); 23 | int m = Integer.parseInt(ip1[1]); 24 | 25 | h = new long[n + 1]; 26 | p = new long[n + 1]; 27 | p[0] = 1; 28 | for (int i = 1; i <= n; i++) { 29 | h[i] = (h[i - 1] * P + (str.charAt(i - 1) - 'a' + 1)) % Long.MAX_VALUE; 30 | p[i] = p[i - 1] * P; 31 | } 32 | 33 | while (m -- > 0) { 34 | int l1, r1, l2, r2; 35 | String[] line = bf.readLine().split(" "); 36 | l1 = Integer.parseInt(line[0]); 37 | r1 = Integer.parseInt(line[1]); 38 | l2 = Integer.parseInt(line[2]); 39 | r2 = Integer.parseInt(line[3]); 40 | 41 | if (query(l1, r1) == query(l2, r2)) System.out.println("Yes"); 42 | else System.out.println("No"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /算法模板代码/并查集.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | static int[] p; 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int n = in.nextInt(); 8 | int m = in.nextInt(); 9 | p = new int[n + 10]; 10 | for (int i = 1; i <= n; i ++) { 11 | p[i] = i; // 让每个元素的父亲是自己 12 | } 13 | while (m -- > 0) { 14 | String o = in.next(); 15 | int a = in.nextInt(); 16 | int b = in.nextInt(); 17 | if ("M".equals(o)) { 18 | p[find(a)] = find(b); 19 | } else { 20 | if (find(a) == find(b)) { 21 | System.out.println("Yes"); 22 | } else { 23 | System.out.println("No"); 24 | } 25 | } 26 | } 27 | } 28 | private static int find(int x) { 29 | if (x != p[x]) { // 父亲不是自己说明还没到根节点 30 | p[x] = find(p[x]); 31 | } 32 | return p[x]; // 返回父亲 33 | } 34 | } 35 | 36 | 作者:luyunix 37 | 链接:https://www.acwing.com/activity/content/code/content/49199/ 38 | 来源:AcWing 39 | 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 -------------------------------------------------------------------------------- /算法模板代码/归并排序.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | public class Main { 6 | public static int[] q, t; 7 | 8 | public static void mergeSort(int[] q, int l, int r) { 9 | if (l >= r) return; 10 | int mid = l + r >> 1; 11 | mergeSort(q, l, mid); mergeSort(q, mid + 1, r); 12 | int k = 0, i = l, j = mid + 1; 13 | while (i <= mid && j <= r) { 14 | if (q[i] < q[j]) t[k++] = q[i++]; 15 | else t[k++] = q[j++]; 16 | } 17 | while (i <= mid) t[k++] = q[i++]; 18 | while (j <= r) t[k++] = q[j++]; 19 | for (i = l, k = 0; i <= r; i++, k++) 20 | q[i] = t[k]; 21 | } 22 | 23 | public static void main(String[] args) throws IOException{ 24 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 25 | String ip1 = bf.readLine(); 26 | String[] ip2 = bf.readLine().split(" "); 27 | int N = Integer.parseInt(ip1); 28 | q = new int[N]; 29 | t = new int[N]; 30 | for (int i = 0; i < N; i++) q[i] = Integer.parseInt(ip2[i]); 31 | mergeSort(q, 0, N - 1); 32 | for (int i = 0; i < N; i++) System.out.printf("%d ", q[i]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /算法模板代码/快速排序.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | public class Main { 6 | public static int[] q; 7 | 8 | public static void quickSort(int[] q, int l, int r) { 9 | if (l >= r) return; 10 | int i = l - 1, j = r + 1, x = q[l]; 11 | while (i < j) { 12 | do i++; while (q[i] < x); 13 | do j--; while (q[j] > x); 14 | if (i < j) { 15 | int t = q[i]; 16 | q[i] = q[j]; 17 | q[j] = t; 18 | } 19 | } 20 | quickSort(q, l, j); 21 | quickSort(q, j + 1, r); 22 | } 23 | 24 | public static void main(String[] args) throws IOException{ 25 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 26 | String[] ip1 = bf.readLine().split(" "); 27 | int N = Integer.parseInt(ip1[0]); 28 | String[] ip2 = bf.readLine().split(" "); 29 | q = new int[N]; 30 | for (int i = 0; i < N; i++) q[i] = Integer.parseInt(ip2[i]); 31 | quickSort(q, 0, N - 1); 32 | for (int i = 0; i < N; i++) System.out.printf("%d ", q[i]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /算法模板代码/最大矩形.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestRectangleArea(int[] heights) { 3 | int n = heights.length; 4 | int[] h, left, right, s; 5 | int tt = 0; 6 | h = new int[n + 2]; 7 | left = new int[n + 2]; // left first number's index smaller than itself 8 | right = new int[n + 2]; // right first number's index smaller than itself 9 | s = new int[n + 2]; 10 | for (int i = 1; i <= n; i++) h[i] = heights[i - 1]; 11 | h[0] = -1; 12 | h[n + 1] = -1; 13 | s[0] = 0; 14 | for (int i = 1; i <= n; i++) { 15 | while (h[s[tt]] >= h[i]) tt--; 16 | left[i] = s[tt]; 17 | s[++tt] = i; 18 | } 19 | tt = 0; 20 | s[0] = n + 1; 21 | for (int i = n; i >= 1; i--) { 22 | while (h[s[tt]] >= h[i]) tt--; 23 | right[i] = s[tt]; 24 | s[++tt] = i; 25 | } 26 | 27 | // get max res 28 | int res = 0; 29 | for (int i = 1; i <= n; i++) { 30 | res = Math.max(res, (right[i] - left[i] - 1) * h[i]); 31 | } 32 | return res; 33 | } 34 | } -------------------------------------------------------------------------------- /算法模板代码/最大连续子数组的和.md: -------------------------------------------------------------------------------- 1 | ## 最大连续子数组的和 2 | 3 | LC53. [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) 4 | 5 | ```java 6 | class Solution { 7 | public int maxSubArray(int[] arr) { 8 | int maxv = arr[0], sum = 0; 9 | for (int i = 0; i < arr.length; i++) { 10 | sum += arr[i]; 11 | maxv = Math.max(maxv, sum); 12 | if (sum < 0) sum = 0; 13 | } 14 | return maxv; 15 | } 16 | } 17 | ``` 18 | 19 | -------------------------------------------------------------------------------- /算法模板代码/最长上升公共子序列.md: -------------------------------------------------------------------------------- 1 | ## 最长上升公共子序列 2 | 3 | #### 输入格式 4 | 5 | 第一行包含一个整数N,表示数列A,B的长度。 6 | 7 | 第二行包含N个整数,表示数列A。 8 | 9 | 第三行包含N个整数,表示数列B。 10 | 11 | #### 输出格式 12 | 13 | 输出一个整数,表示最长公共上升子序列的长度。 14 | 15 | #### 数据范围 16 | 17 | 1≤N≤3000,序列中的数字均不超过2^31−1 18 | 19 | #### 输入样例: 20 | 21 | ``` 22 | 4 23 | 2 2 1 3 24 | 2 1 2 3 25 | ``` 26 | 27 | #### 输出样例: 28 | 29 | ``` 30 | 2 31 | ``` 32 | 33 | ### 代码 34 | 35 | ```cpp 36 | #include 37 | #include 38 | #include 39 | 40 | using namespace std; 41 | 42 | const int N = 3010; 43 | 44 | int n; 45 | int a[N], b[N]; 46 | int f[N][N]; 47 | 48 | int main() 49 | { 50 | scanf("%d", &n); 51 | for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]); 52 | for (int i = 1; i <= n; i ++ ) scanf("%d", &b[i]); 53 | 54 | for (int i = 1; i <= n; i ++ ) 55 | { 56 | int maxv = 1; 57 | for (int j = 1; j <= n; j ++ ) 58 | { 59 | f[i][j] = f[i - 1][j]; 60 | if (a[i] == b[j]) f[i][j] = max(f[i][j], maxv); 61 | if (a[i] > b[j]) maxv = max(maxv, f[i][j] + 1); 62 | } 63 | } 64 | 65 | int res = 0; 66 | for (int i = 1; i <= n; i ++ ) res = max(res, f[n][i]); 67 | printf("%d\n", res); 68 | 69 | return 0; 70 | } 71 | ``` 72 | 73 | -------------------------------------------------------------------------------- /算法模板代码/最长连续不重复的子序列.md: -------------------------------------------------------------------------------- 1 | ## 最长连续不重复的子序列 2 | 3 | https://www.acwing.com/problem/content/description/801/ 4 | 5 | 给定一个长度为 n 的整数序列,请找出最长的不包含重复的数的连续区间,输出它的长度。 6 | 7 | #### 输入格式 8 | 9 | 第一行包含整数 nn。 10 | 11 | 第二行包含 n 个整数(均在 0∼10^5范围内),表示整数序列。 12 | 13 | #### 输出格式 14 | 15 | 共一行,包含一个整数,表示最长的不包含重复的数的连续区间的长度。 16 | 17 | #### 数据范围 18 | 19 | 1≤n≤10 20 | 21 | #### 输入样例: 22 | 23 | ``` 24 | 5 25 | 1 2 2 3 5 26 | ``` 27 | 28 | #### 输出样例: 29 | 30 | ``` 31 | 3 32 | ``` 33 | 34 | ### 代码 35 | 36 | ```cpp 37 | #include 38 | using namespace std; 39 | 40 | const int N = 100005; 41 | int q[N], f[N]; // q[N]为数组,f[N]记录出现次数 42 | 43 | int main() 44 | { 45 | int n; 46 | scanf("%d", &n); 47 | for (int i = 0; i < n; i++) scanf("%d", &q[i]); 48 | int res = 0; 49 | for (int i = 0, j = 0; i < n; i++) { 50 | f[q[i]]++; 51 | while (j < i && f[q[i]] > 1) f[q[j ++]] --; 52 | res = max(res, i - j + 1); 53 | } 54 | printf("%d", res); 55 | } 56 | ``` 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /算法模板代码/模拟散列表.java: -------------------------------------------------------------------------------- 1 | static class MyHashMap{ 2 | int N=100003; 3 | int[]h; 4 | public MyHashMap(){ 5 | h=new int[N]; 6 | for(int i=0;i= h[i]) tt--; 15 | left[i] = s[tt]; 16 | s[++tt] = i; 17 | } 18 | tt = 0; 19 | s[0] = n + 1; 20 | for (int i = n; i >= 1; i--) { 21 | while (h[s[tt]] >= h[i]) tt--; 22 | right[i] = s[tt]; 23 | s[++tt] = i; 24 | } 25 | for (int i = 1; i <= n; i++) { 26 | res = Math.max(res, (right[i] - left[i] - 1) * h[i]); 27 | } 28 | return res; 29 | } 30 | } --------------------------------------------------------------------------------