You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0100-0199/0180.Consecutive Numbers/README_EN.md
+19-6
Original file line number
Diff line number
Diff line change
@@ -53,31 +53,44 @@ Logs table:
53
53
54
54
## Solutions
55
55
56
-
**Solution 1: Window Function**
56
+
**Solution 1: Two Joins**
57
57
58
-
We can use the window functions `LAG` and `LEAD`to determine whether the previous row and the next row of the current row are equal to the `num` of the current row. If the `num` of the current row is equal to the `num` of the previous row, we set the field $a$ to $1$, otherwise we set it to $0$; if the `num` of the current row is equal to the `num` of the next row, we set the field $b$ to $1$, otherwise we set it to $0$.
58
+
We can use two joins to solve this problem.
59
59
60
-
Finally, we only need to filter out the rows where $a = 1$ and $b = 1$, which are the numbers that appear at least three times in a row. Note that we need to use the `DISTINCT` keyword to remove duplicates from the results.
60
+
First, we perform a self-join with the condition `l1.num = l2.num` and `l1.id = l2.id - 1`, so that we can find all numbers that appear at least twice in a row. Then, we perform another self-join with the condition `l2.num = l3.num` and `l2.id = l3.id - 1`, so that we can find all numbers that appear at least three times in a row. Finally, we only need to select the distinct `l2.num`.
61
+
62
+
**Solution 2: Window Function**
63
+
64
+
We can use the window functions `LAG` and `LEAD` to obtain the `num` of the previous row and the next row of the current row, and record them in the fields $a$ and $b$, respectively. Finally, we only need to filter out the rows where $a = num$ and $b = num$, which are the numbers that appear at least three times in a row. Note that we need to use the `DISTINCT` keyword to remove duplicates from the results.
61
65
62
66
We can also group the numbers by using the `IF` function to determine whether the `num` of the current row is equal to the `num` of the previous row. If they are equal, we set it to $0$, otherwise we set it to $1$. Then, we use the window function `SUM` to calculate the prefix sum, which is the grouping identifier. Finally, we only need to group by the grouping identifier and filter out the numbers with a row count greater than or equal to $3$ in each group. Similarly, we need to use the `DISTINCT` keyword to remove duplicates from the results.
0 commit comments