This article is the solution Data Structures: Thought Process from HashMap to HashMap + Array of Problem 380. Insert Delete GetRandom O(1).
It’s easy to think of using a Hash Table to achieve $O(1)$ time complexity for $\texttt{insert}$ and $\texttt{remove}$ operations. However, we need $O(1)$ time complexity to complete the $\texttt{getRandom}$ operation.
The Array structure can complete the operation of obtaining random elements in $O(1)$ time complexity, but it can’t completed the $\texttt{insert}$ and $\texttt{remove}$ operations in $O(1)$ time complexity.
So How?
Aha!!!
We can combining the $\texttt{HashMap}$ and Array. The Array stores the elements, and the $\texttt{HashMap}$ stores the input value as the $\texttt{key}$ and the array subscript $\texttt{loc}$ as the value.
We need to apply for an array nums of sufficient size (the data range is $2 \times 10^5$ ), and a variable $\texttt{idx}$ to record how many space is currently used.
$\texttt{insert}$: Judge whether the $\texttt{HashMap}$ contains the $\texttt{val}$, if not, insert the $\texttt{val}$ to the $\texttt{HashMap}$ and update the Array nums.
$\texttt{remove}$: Judge whether the $\texttt{HashMap}$ contains the $\texttt{val}$, if not, get the location loc of the input val, replace the loc with the last value of the array, remove the $\texttt{val}$ from $\texttt{HashMap}$ and update the $\texttt{idx}$.
$\texttt{getRandom}$: Just select a subscript at random and return the element of the array.
1  class RandomizedSet { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution Data Structures: Thought Process from HashMap to HashMap + Array of Problem 380. Insert Delete GetRandom O(1).
It’s easy to think of using a Hash Table to achieve $O(1)$ time complexity for $\texttt{insert}$ and $\texttt{remove}$ operations. However, we need $O(1)$ time complexity to complete the $\texttt{getRandom}$ operation.
The Array structure can complete the operation of obtaining random elements in $O(1)$ time complexity, but it can’t completed the $\texttt{insert}$ and $\texttt{remove}$ operations in $O(1)$ time complexity.
So How?
Aha!!!
]]>今天 LeetCode 第320场周赛 中第一题是 2475. 数组中不等三元组的数目 ，本文是该题的题解，同时发表在 这里 。
参考了 @灵茶山艾府 的题解 非暴力做法 ，实际上我们可以不用先排序，而是先用 $\texttt{HashMap}$ 统计数组 $\textit{num}$ 元素频率。
之后遍历 $\texttt{HashMap}$ ，结果为：$\sum_{j = 0}^{n} (map[0] + \cdots + map[i]) \times map[j] \times (map[k] + \cdots + map[n  1])$ ，其中 $n$ 为 $\textit{nums}$ 的长度。
证明如下：
对于数组中的元素 $x$ ，可以得到：
那么 $x$ 对最终答案的贡献是 $abc$ 。
即使 $x$ 是三元组中的最大或最小值，由于 $i, j, k$ 的对称性，很明显其实和 $x$ 是中间值都是同一个答案。
证毕！
1  class Solution { 
在方法一的基础上，实际上我们还有一种更快的方法，就是利用中学数学里学过的 排列组合 .
详细题解：The Fastest O(n) Solution: Math Combinations 。
代码如下所示：
1  class Solution { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>今天 LeetCode 第320场周赛 中第一题是 2475. 数组中不等三元组的数目 ，本文是该题的题解，同时发表在 这里 。
参考了 @灵茶山艾府 的题解 非暴力做法 ，实际上我们可以不用先排序，而是先用 $\texttt{HashMap}$ 统计数组 $\textit{num}$ 元素频率。
之后遍历 $\texttt{HashMap}$ ，结果为：$\sum_{j = 0}^{n} (map[0] + \cdots + map[i]) \times map[j] \times (map[k] + \cdots + map[n  1])$ ，其中 $n$ 为 $\textit{nums}$ 的长度。
证明如下：
对于数组中的元素 $x$ ，可以得到：
那么 $x$ 对最终答案的贡献是 $abc$ 。
即使 $x$ 是三元组中的最大或最小值，由于 $i, j, k$ 的对称性，很明显其实和 $x$ 是中间值都是同一个答案。
证毕！
]]>This article is the solution It is Literally a Graph: DFS and Union Find of Problem 947. Most Stones Removed with Same Row or Column.
We can find that this is a graph theory problem with analysis.
Imagine the stone on the 2D coordinate plane as the vertex of the graph, If the xcoord or the ycoord of two stones are the same, there is an edge between them.
This can be show as follows:
According to the rule that stones can be removed, we should remove those points that are in the same row or column with other points as late as possible. That is, the more points in the same row or column with point A, the later point A should be removed. In this way, we can delete as many points as possible through point A.
It can be found that all vertices in a connected graph can be deleted to only one vertex.
Since these vertices are in a connected graph, all vertices of the connected graph can be traversed by DFS or BFS.
Therefore: the maximum number of stones that can be removed = the number of all stones  the number of connected components.
1  class Solution { 
O(n^2)
.O(n)
.1  class Solution { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution It is Literally a Graph: DFS and Union Find of Problem 947. Most Stones Removed with Same Row or Column.
We can find that this is a graph theory problem with analysis.
Imagine the stone on the 2D coordinate plane as the vertex of the graph, If the xcoord or the ycoord of two stones are the same, there is an edge between them.
This can be show as follows:
According to the rule that stones can be removed, we should remove those points that are in the same row or column with other points as late as possible. That is, the more points in the same row or column with point A, the later point A should be removed. In this way, we can delete as many points as possible through point A.
It can be found that all vertices in a connected graph can be deleted to only one vertex.
Since these vertices are in a connected graph, all vertices of the connected graph can be traversed by DFS or BFS.
Therefore: the maximum number of stones that can be removed = the number of all stones  the number of connected components.
]]>This article is the solution Two Heaps with the Follow Up’s Solution of Problem 295. Find Median from Data Stream.
We can simply use a $\texttt{ArrayList}$ to record the number and sort the list, then we can easily get the median element of the list. However, the Time Complexity will be $O(n^2logn)$ and the Space Complexity is $O(n)$.
It surely will be TLE and we have to find a better solution.
We can use Two Priority Queues (Heaps) to maintain the data of the entire data stream.
The min Heap denoted as $\textit{queueMin}$ is used to maintain the number $\textit{num} \leq \textit{median}$. The max Heap denoted as $\textit{queueMax}$ is used to maintain the number $\textit{num} \gt \textit{median}$.
When the total number of data stream elements is Even: $\texttt{queueMax.size()} = \texttt{queueMin.size()}$, the dynamic median is $\frac{\texttt{queueMax.peek()} + \texttt{queueMin.peek()}}{2}$;
When the total number of data stream elements is Odd: $\texttt{queueMin.size()} = \texttt{queueMin.size()} + 1$, the dynamic median is $\texttt{queueMin.peek()}$.
When we try to add a new number $\textit{num}$ to the Two Heaps, the cases can be as follows:
We need to add this number to $\textit{queueMin}$. The new median will be less than or equal to the original median, so we may need to move the $\texttt{queueMin.peek()}$ to $\textit{queueMax}$.
We need to add this number to $\textit{queueMax}$. The new median will be greater than or equal to the original median, so we may need to move the $\texttt{queueMax.peek()}$ to $\textit{queueMin}$.
1  static class MedianFinder { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution Two Heaps with the Follow Up’s Solution of Problem 295. Find Median from Data Stream.
We can simply use a $\texttt{ArrayList}$ to record the number and sort the list, then we can easily get the median element of the list. However, the Time Complexity will be $O(n^2logn)$ and the Space Complexity is $O(n)$.
It surely will be TLE and we have to find a better solution.
We can use Two Priority Queues (Heaps) to maintain the data of the entire data stream.
The min Heap denoted as $\textit{queueMin}$ is used to maintain the number $\textit{num} \leq \textit{median}$. The max Heap denoted as $\textit{queueMax}$ is used to maintain the number $\textit{num} \gt \textit{median}$.
When the total number of data stream elements is Even: $\texttt{queueMax.size()} = \texttt{queueMin.size()}$, the dynamic median is $\frac{\texttt{queueMax.peek()} + \texttt{queueMin.peek()}}{2}$;
When the total number of data stream elements is Odd: $\texttt{queueMin.size()} = \texttt{queueMin.size()} + 1$, the dynamic median is $\texttt{queueMin.peek()}$.
今天 LeetCode CN 的每日一题是 1668. 最大重复子字符串 ，本文是该题的题解，同时发表在 这里 。
这道题有好几个方法：
API 方法最简单，但 KMP 算法比较复杂。看了一些题解里的暴力解法，大多数人的暴力解法写的太复杂。我自己写该题暴力解法也写了 $3$ 个版本，前 $2$ 个版本也很复杂，逐渐优化为目前的简洁优雅版本。
暴力解法使用 $2$ 个循环，第 $1$ 个循环，遍历 $\textit{sequence}$ 中的每个字符，判断是否和 $\texttt{word.charAt(0)}$ 相同，相同的话的进入下一步；
使用一个索引 $j$ ，$0 \le j \le len  i$ ，而这里 $\textit{word}$ 字符索引可以使用 $j \mod wLen$ 来获取，这是暴力解法中最优雅的地方。如果遇到不相同的字符，跳出循环。
最后更新最大重复子字符串，就是 $\textit{ans}$ 和 $j / wLen$ 的更大值。
中间其实还可以剪枝，但由于数据量比较小，就不加了。
代码如下所示：
1  class Solution { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>今天 LeetCode CN 的每日一题是
This article is the solution Why Greedy Works? of Problem 334. Increasing Triplet Subsequence.
We can easily find that whether there exists a triple of indices $(i, j, k)$ such that $i < j < k$ and $nums[i] < \textit{nums}[j] < \textit{nums}[k]$ only traversing the array once, but the problem is how to make our mind into algorithms.
It’s easy to use Brute Force way to solve this problem, but the time complexity is $O(n^3)$, it will TLE, so we need to find a better way.
1  public static boolean increasingTriplet(int[] nums) { 
We can also use DP method to solve it.
Let $dp[i]$ represents the maximum length of a increasing sequence.
$dp[i] = \begin{cases} 1 & dp[i] \le dp[j], 0 < j < i \\ dp[j] + 1 & dp[i] > dp[j], 0 < j < i \end{cases}$
We can reduce the time complexity to $O(n^2)$, but it still will TLE.
1  public boolean increasingTriplet(int[] nums) { 
When traversing the array $\textit{nums}[j]$, $0 < j < n − 1$, if there is an element on the left of $\textit{nums}[i] < \textit{nums}[j]$, $0 \le i < j$, and an element on the right of $\textit{nums}[k]$, $j < k < len$.
Therefore, we can maintain the minimum value on the left and the maximum value on the right of each element in the array.
1  // time: O(n) space: O(n) 
We can easily know that we can find the answer with just traverse the array once.
Assuming that we already have two numbers $\textit{first}$ and $\textit{second}$, with $\textit{second} > \textit{first}$, now we have to find the $\textit{third}$ number while traversing the array.
The $third$ number can be as follows:
If $\textit{third} > \textit{second}$, we have found it and return true directly.
If $\textit{third} < \textit{second}$ && $\textit{third} > \textit{first}$, we make $\textit{second} = \textit{third}$, and continue traversing the rest array to find the $third$ number.
If $\textit{third} < \textit{first}$, we make $\textit{first} = \textit{third}$, and then continue to search for the $\textit{third}$.
The trick is here.
You would worry that the $\textit{first}$ is now behind the $\textit{second}$. Image if we meet $\textit{third} > \textit{second}$, we can use the old $\textit{first}$ that meets $\textit{first} < \textit{second} < \textit{third}$.
We make $\textit{first} = \textit{third}$, we can select a lower $\textit{second}$ and $\textit{third}$ because the $\textit{first}$ become smaller.
1  // time: O(n) space: O(1) 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution Why Greedy Works? of Problem 334. Increasing Triplet Subsequence.
We can easily find that whether there exists a triple of indices $(i, j, k)$ such that $i < j < k$ and $nums[i] < \textit{nums}[j] < \textit{nums}[k]$ only traversing the array once, but the problem is how to make our mind into algorithms.
It’s easy to use Brute Force way to solve this problem, but the time complexity is $O(n^3)$, it will TLE, so we need to find a better way.
1  public static boolean increasingTriplet(int[] nums) { 
We can also use DP method to solve it.
Let $dp[i]$ represents the maximum length of a increasing sequence.
$dp[i] = \begin{cases} 1 & dp[i] \le dp[j], 0 < j < i \\ dp[j] + 1 & dp[i] > dp[j], 0 < j < i \end{cases}$
]]>224. 基本计算器
227. 基本计算器 II
772. 基本计算器 III
1 
1 
1 
224. 基本计算器
490. 迷宫 Medium
505. 迷宫 II Medium
499. 迷宫 III Hard
1  class Solution { 
1  class Solution { 
1  class Solution { 
1  class Solution { 
1  class Solution { 
1  class Solution { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>490. 迷宫 Medium
505. 迷宫 II Medium
499. 迷宫 III Hard
1  class Solution { 
1  public static int numIslands_bfs(char[][] grid) { 
1  class Solution { 
1  class Solution { 
1  class Solution { 
1  public static int numIslands_bfs(char[][] grid) { 
1  class Solution { 
252. 会议室
253. 会议室 II
2402. 会议室 III
1  public static boolean canAttendMeetings_bf(int[][] intervals) { 
1  public static boolean canAttendMeetings(int[][] intervals) { 
1  public int minMeetingRooms(int[][] intervals) { 
todo
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>252. 会议室
253. 会议室 II
2402. 会议室 III
1  public static boolean canAttendMeetings_bf(int[][] intervals) { 
1  public static boolean canAttendMeetings(int[][] intervals) { 
This article is the solution 4 Approaches: Two Pointers, Sorting, Priority Queue and Binary Search of Problem 658. Find K Closest Elements.
Here shows 4 Approaches to slove this problem: Two Pointers, Sorting, Priority Queue and Binary Search with Two Pointers.
1  // TP time: O(n) space: O(1) 
1  // Sort time: O(nlogn) space: O(logn) 
1  public List<Integer> findClosestElements(int[] arr, int k, int x) { 
Since the array is sorted, so it’s easy to use the Binary Search method to find the closest element of $\textit{x}$, then we start to find the other closest elements both the left and right.
1  // BinarySearch time: O(n) space: O(1) 
The code is too obscure, we can just find the closest element which gt than $\textit{x}$, then use two pointers to search other $\textit{k}$ elements from both sides.
1  // BinarySearch Opt time: O(logn+k) space: O(1) 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution 4 Approaches: Two Pointers, Sorting, Priority Queue and Binary Search of Problem 658. Find K Closest Elements.
Here shows 4 Approaches to slove this problem: Two Pointers, Sorting, Priority Queue and Binary Search with Two Pointers.
1  // TP time: O(n) space: O(1) 
This article is the solution 3 Approaches: Brute Force, Stack, Slow Fast Pointers with Animation of Problem 19. Remove Nth Node From End of List.
Here shows 3 Approaches to slove this problem: Brute Force, Stack, Slow Fast Pointers.
It’s easy to think of the way that we traverse the linked list first, from the head node to the end node, to get the length of the linked list $L$.
Then we traverse the linked list from the head node again. When the $Ln+1$ th node is traversed, it is the node we need to delete.
We can traverse $Ln+1$ nodes starting from the dummy node. When traversing to the $Ln+1$th node, its next node is the node we need to delete, so we only need to modify the pointer once to complete the deletion operation.
1  public static ListNode removeNthFromEnd(ListNode head, int n) { 
We can also push all nodes on the stack one by one while traversing the linked list.
As the stack is FILO, the nth
node we pop out of the stack is the node that needs to be deleted, and the node at the top of the stack is the predecessor node of the node to be deleted.
In this way, the deletion operation becomes very convenient.
1  public static ListNode removeNthFromEnd(ListNode head, int n) { 
As the animation shows below:
1  public static ListNode removeNthFromEnd(ListNode head, int n) { 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution 3 Approaches: Brute Force, Stack, Slow Fast Pointers with Animation of Problem 19. Remove Nth Node From End of List.
Here shows 3 Approaches to slove this problem: Brute Force, Stack, Slow Fast Pointers.
It’s easy to think of the way that we traverse the linked list first, from the head node to the end node, to get the length of the linked list $L$.
Then we traverse the linked list from the head node again. When the $Ln+1$ th node is traversed, it is the node we need to delete.
We can traverse $Ln+1$ nodes starting from the dummy node. When traversing to the $Ln+1$th node, its next node is the node we need to delete, so we only need to modify the pointer once to complete the deletion operation.
1  public static ListNode removeNthFromEnd(ListNode head, int n) { 
This article is the solution From Brute Force to DP to Two Pointers with Detail Explaination of Problem 42. Trapping Rain Water.
It’s like Leetcode 11. Container With Most Water , we can consider the black block as a wall, the blue block as water. Given an array, each element represents the height of the wall from left to right, find out how many units of water can be held.
The solution can be refered 2 Approaches: BF and Two Pointers with Image Explaination .
It’s easy to use the brute force approach. The time complexity is $O(max^n)$, so it will TLE.
1  // Row time: O(max * n) space: O(1) 
To find the water in each column, we only need to focus on:
To find how much water filled, we only need to look at the shorter one of the tallest wall on the left and the tallest wall on the right.
Therefore, according to the height of the shorter wall and the wall of the current column, it can be divided into three cases.
Imagine pouring water between the tallest walls on either side. How much water will the column being asked for?
Obviously, the shorter side, which is the height of the wall on the left, minus the height of the current column, which is $2  1 = 1$, can store one unit of water.
Imagine pouring water between the tallest walls on either side. How much water will the column being asked for?
The column being sought will not have water because it is larger than the lower walls on either side.
As in the previous case, there will be no water.
1  // Col time: O(n^2) space: O(1) 
In Approache 2, for each column, we have to traverse all the heights to get the tallest wall on the left and the tallest wall on the right, we can optimize it.
We can use extra space to tradeoff the time complexity.
Use two arrays, $max_left[i]$ and $max_right[i]$, which represents the height of the tallest wall on the left or right of column $i$.
$max_left[i] = Max(max_left[i1], height[i1])$. Choose the higher height on the left side of the wall in front of it and the height of the wall in front of it, which is the highest wall on the left side of the current column.
$max_right[i] = Max(max_right[i+1],height[i+1])$. The highest height on the right side of the wall behind it and the height of the wall behind it choose a larger one, which is the highest wall on the right side of the current column.
1  // DP time: O(n) space: O(n) 
In DP Approach, we can often optimize the space complexity.
We can see that the elements in the $max_left[i]$ and $max_right[i]$ arrays are actually only used once, and then never used again. So we can use just use one element instead of an array.
1  // Two Pointers time: O(n) space: O(1) 
All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:)
Explore More Leetcode Solutions. 😉😃💗
]]>This article is the solution From Brute Force to DP to Two Pointers with Detail Explaination of Problem 42. Trapping Rain Water.
It’s like Leetcode 11. Container With Most Water , we can consider the black block as a wall, the blue block as water. Given an array, each element represents the height of the wall from left to right, find out how many units of water can be held.
The solution can be refered 2 Approaches: BF and Two Pointers with Image Explaination .
It’s easy to use the brute force approach. The time complexity is $O(max^n)$, so it will TLE.
1  // Row time: O(max * n) space: O(1) 
1 
]]>
参考资料]]>参考资料
