Skip to content

Commit b7d2658

Browse files
authored
feat: add solutions to lc problems: No.1385+ (doocs#2159)
1 parent 201b8e9 commit b7d2658

File tree

27 files changed

+284
-71
lines changed

27 files changed

+284
-71
lines changed

solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ For arr1[2]=8 we have:
5757

5858
## Solutions
5959

60+
**Solution 1: Sorting + Binary Search**
61+
62+
We can first sort the array $arr2$, then for each element $a$ in array $arr1$, use binary search to find the first element in array $arr2$ that is greater than or equal to $a-d$. If such an element exists and is less than or equal to $a+d$, it means that it does not meet the distance requirement. Otherwise, it meets the distance requirement. We accumulate the number of elements that meet the distance requirement, which is the answer.
63+
64+
The time complexity is $O((m + n) \times \log n)$, and the space complexity is $O(\log n)$. Where $m$ and $n$ are the lengths of arrays $arr1$ and $arr2$, respectively.
65+
6066
<!-- tabs:start -->
6167

6268
### **Python3**

solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md

+14
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,20 @@
5151

5252
## Solutions
5353

54+
**Solution 1: Hash Table + Bit Manipulation**
55+
56+
We use a hash table $d$ to store all the reserved seats, where the key is the row number, and the value is the state of the reserved seats in that row, i.e., a binary number. The $j$-th bit being $1$ means the $j$-th seat is reserved, and $0$ means the $j$-th seat is not reserved.
57+
58+
We traverse $reservedSeats$, for each seat $(i, j)$, we add the state of the $j$-th seat (corresponding to the $10-j$ bit in the lower bits) to $d[i]$.
59+
60+
For rows that do not appear in the hash table $d$, we can arrange $2$ families arbitrarily, so the initial answer is $(n - len(d)) \times 2$.
61+
62+
Next, we traverse the state of each row in the hash table. For each row, we try to arrange the situations $1234, 5678, 3456$ in turn. If a situation can be arranged, we add $1$ to the answer.
63+
64+
After the traversal, we get the final answer.
65+
66+
The time complexity is $O(m)$, and the space complexity is $O(m)$. Where $m$ is the length of $reservedSeats$.
67+
5468
<!-- tabs:start -->
5569

5670
### **Python3**

solution/1300-1399/1387.Sort Integers by The Power Value/README_EN.md

+10
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ The fourth number in the sorted array is 7.
5353

5454
## Solutions
5555

56+
**Solution 1: Custom Sorting**
57+
58+
First, we define a function $f(x)$, which represents the number of steps required to change the number $x$ to $1$, i.e., the weight of the number $x$.
59+
60+
Then, we sort all the numbers in the interval $[lo, hi]$ in ascending order of weight. If the weights are the same, we sort them in ascending order of the numbers themselves.
61+
62+
Finally, we return the $k$-th number after sorting.
63+
64+
The time complexity is $O(n \times \log n \times M)$, and the space complexity is $O(n)$. Where $n$ is the number of numbers in the interval $[lo, hi]$, and $M$ is the maximum value of $f(x)$. In this problem, the maximum value of $M$ is $178$.
65+
5666
<!-- tabs:start -->
5767

5868
### **Python3**

solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md

+29
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,35 @@
4343

4444
## Solutions
4545

46+
**Solution 1: Dynamic Programming**
47+
48+
We can transform this problem into: In a circular array of length $3n$, select $n$ non-adjacent numbers so that the sum of these $n$ numbers is maximized.
49+
50+
The proof is as follows:
51+
52+
- When $n = 1$, we can choose any number in the array.
53+
- When $n > 1$, there must exist a number such that there are two consecutive numbers on one side of it that have not been selected, and at least one number on the other side has not been selected. Therefore, we can remove this number and the numbers on both sides of it from the array, and then the remaining $3(n - 1)$ numbers form a new circular array. The problem scale is reduced to selecting $n - 1$ non-adjacent numbers in a circular array of length $3(n - 1)$, so that the sum of these $n - 1$ numbers is maximized.
54+
55+
Therefore, the problem we need to solve can be transformed into: In a circular array of length $3n$, select $n$ non-adjacent numbers so that the sum of these $n$ numbers is maximized.
56+
57+
In a circular array, if the first number is selected, the last number cannot be selected. If the last number is selected, the first number cannot be selected. Therefore, we can split the circular array into two arrays, one is without the first number, and the other is without the last number. Then solve the maximum value of these two arrays separately, and finally take the larger of the two maximum values.
58+
59+
We use a function $g(nums)$, which represents the maximum sum of selecting $n$ non-adjacent numbers in the array $nums$. Then our goal is to find the larger value between $g(slices)$ and $g(slices[1:])$.
60+
61+
The solution method of function $g(nums)$ is as follows:
62+
63+
We denote the length of array $nums$ as $m$, and define $f[i][j]$ as the maximum sum of selecting $j$ non-adjacent numbers in the first $i$ numbers of array $nums$.
64+
65+
Consider $f[i][j]$, if we do not select the $i$-th number, then $f[i][j] = f[i - 1][j]$. If we select the $i$-th number, then $f[i][j] = f[i - 2][j - 1] + nums[i - 1]$. Therefore, we can get the state transition equation:
66+
67+
$$
68+
f[i][j] = \max(f[i - 1][j], f[i - 2][j - 1] + nums[i - 1])
69+
$$
70+
71+
Finally, return $f[m][n]$.
72+
73+
The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array $slices$.
74+
4675
<!-- tabs:start -->
4776

4877
### **Python3**

solution/1300-1399/1389.Create Target Array in the Given Order/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,12 @@ nums index target
6464

6565
## Solutions
6666

67+
**Solution 1: Simulation**
68+
69+
We create a list $target$ to store the target array. Since the problem guarantees that the insertion position always exists, we can directly insert in the given order into the corresponding position.
70+
71+
The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.
72+
6773
<!-- tabs:start -->
6874

6975
### **Python3**

solution/1300-1399/1390.Four Divisors/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ The answer is the sum of divisors of 21 only.
4343

4444
## Solutions
4545

46+
**Solution 1: Factor Decomposition**
47+
48+
We can perform factor decomposition on each number. If the number of factors is $4$, then this number meets the requirements of the problem, and we can add its factors to the answer.
49+
50+
The time complexity is $O(n \times \sqrt{n})$, where $n$ is the length of the array. The space complexity is $O(1)$.
51+
4652
<!-- tabs:start -->
4753

4854
### **Python3**

solution/1300-1399/1392.Longest Happy Prefix/README_EN.md

+10
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@
3535

3636
## Solutions
3737

38+
**Solution 1: String Hashing**
39+
40+
**String Hashing** is a method to map a string of any length to a non-negative integer, with the probability of collision being almost zero. String hashing is used to calculate the hash value of a string, which allows for quick determination of whether two strings are equal.
41+
42+
We choose a fixed value BASE, and consider the string as a number in BASE radix, assigning a value greater than 0 to represent each character. Generally, the values we assign are much smaller than BASE. For example, for strings composed of lowercase letters, we can assign a=1, b=2, ..., z=26. We choose a fixed value MOD, and calculate the remainder of the BASE radix number divided by MOD, which is used as the hash value of the string.
43+
44+
Generally, we choose BASE=131 or BASE=13331, at which point the probability of hash value collision is extremely low. As long as the hash values of two strings are the same, we consider the two strings to be equal. Usually, MOD is chosen as $2^{64}$. In C++, we can directly use the unsigned long long type to store this hash value. When calculating, we do not handle arithmetic overflow. When overflow occurs, it is equivalent to automatically taking the modulus of $2^{64}$, which can avoid inefficient modulus operations.
45+
46+
Except for extremely specially constructed data, the above hash algorithm is unlikely to produce collisions. In general, the above hash algorithm can appear in the standard answers of the problem. We can also choose some appropriate values of BASE and MOD (such as large prime numbers), and perform several groups of hash operations. Only when the results are all the same do we consider the original strings to be equal, making it even more difficult to construct data that causes this hash to produce errors.
47+
3848
<!-- tabs:start -->
3949

4050
### **Python3**

solution/1300-1399/1393.Capital GainLoss/README_EN.md

+4
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$.
6767

6868
## Solutions
6969

70+
**Solution 1: GROUP BY + SUM(IF())**
71+
72+
We use `GROUP BY` to group the buy and sell operations of the same stock, and then use `SUM(IF())` to calculate the capital gains and losses of each stock.
73+
7074
<!-- tabs:start -->
7175

7276
### **SQL**

solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@
4343

4444
## Solutions
4545

46+
**Solution 1: Counting**
47+
48+
We can use a hash table or array $cnt$ to count the occurrences of each number in $arr$, then traverse $cnt$ to find the largest $x$ that satisfies $cnt[x] = x$. If there is no such $x$, return $-1$.
49+
50+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of $arr$.
51+
4652
<!-- tabs:start -->
4753

4854
### **Python3**

solution/1300-1399/1395.Count Number of Teams/README_EN.md

+12
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,18 @@
5151

5252
## Solutions
5353

54+
**Solution 1: Enumerate Middle Element**
55+
56+
We can enumerate each element $rating[i]$ in the array $rating$ as the middle element, then count the number of elements $l$ that are smaller than it on the left, and the number of elements $r$ that are larger than it on the right. The number of combat units with this element as the middle element is $l \times r + (i - l) \times (n - i - 1 - r)$. We can add this to the answer.
57+
58+
The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Where $n$ is the length of the array $rating$.
59+
60+
**Solution 2: Binary Indexed Tree**
61+
62+
We can use two binary indexed trees to maintain the number of elements $l$ that are smaller than each element on the left in the array $rating$, and the number of elements $r$ that are larger than it on the right. Then count the number of combat units with this element as the middle element as $l \times r + (i - l) \times (n - i - 1 - r)$, and add this to the answer.
63+
64+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $rating$.
65+
5466
<!-- tabs:start -->
5567

5668
### **Python3**

solution/1300-1399/1396.Design Underground System/README_EN.md

+15
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,21 @@ undergroundSystem.getAverageTime(&quot;Leyton&quot;, &quot;Paradise&quot;); // r
9595

9696
## Solutions
9797

98+
**Solution 1: Hash Table**
99+
100+
We use two hash tables to store data:
101+
102+
- `ts`: Stores the passenger's id, check-in time, and check-in station. The key is the passenger's id, and the value is a tuple `(t, stationName)`.
103+
- `d`: Stores the passenger's check-in station, check-out station, travel time, and number of trips. The key is a tuple `(startStation, endStation)`, and the value is a tuple `(totalTime, count)`.
104+
105+
When a passenger checks in, we store the passenger's id, check-in time, and check-in station in `ts`, i.e., `ts[id] = (t, stationName)`.
106+
107+
When a passenger checks out, we retrieve the passenger's check-in time and station `(t0, station)` from `ts`, then calculate the passenger's travel time $t - t_0$, and store the passenger's travel time and number of trips in `d`.
108+
109+
When we want to calculate a passenger's average travel time, we retrieve the passenger's total travel time and number of trips `(totalTime, count)` from `d`, then calculate the average travel time as $totalTime / count$.
110+
111+
The time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is the number of passengers.
112+
98113
<!-- tabs:start -->
99114

100115
### **Python3**

solution/1300-1399/1399.Count Largest Group/README_EN.md

+10
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ There are 4 groups with largest size.
3838

3939
## Solutions
4040

41+
**Solution 1: Hash Table or Array**
42+
43+
We note that the number does not exceed $10^4$, so the sum of the digits also does not exceed $9 \times 4 = 36$. Therefore, we can use a hash table or an array of length $40$, denoted as $cnt$, to count the number of each sum of digits, and use a variable $mx$ to represent the maximum count of the sum of digits.
44+
45+
We enumerate each number in $[1,..n]$, calculate its sum of digits $s$, then increment $cnt[s]$ by $1$. If $mx < cnt[s]$, we update $mx = cnt[s]$ and set $ans$ to $1$. If $mx = cnt[s]$, we increment $ans$ by $1$.
46+
47+
Finally, we return $ans$.
48+
49+
The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log M)$. Where $n$ is the given number, and $M$ is the range of $n$.
50+
4151
<!-- tabs:start -->
4252

4353
### **Python3**

solution/1400-1499/1400.Construct K Palindrome Strings/README_EN.md

+8
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ Some possible constructions &quot;anna&quot; + &quot;elble&quot;, &quot;anbna&qu
4343

4444
## Solutions
4545

46+
**Solution 1: Counting**
47+
48+
First, we check if the length of string $s$ is less than $k$. If it is, we cannot construct $k$ palindrome strings, so we can directly return `false`.
49+
50+
Otherwise, we use a hash table or an array $cnt$ to count the occurrences of each character in string $s$. Finally, we only need to count the number of characters $x$ that appear an odd number of times in $cnt$. If $x$ is greater than $k$, we cannot construct $k$ palindrome strings, so we return `false`; otherwise, we return `true`.
51+
52+
The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of string $s$, and $C$ is the size of the character set, here $C=26$.
53+
4654
<!-- tabs:start -->
4755

4856
### **Python3**

solution/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md

+18
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,24 @@
4343

4444
## Solutions
4545

46+
**Solution 1: Mathematics**
47+
48+
For a point $(x, y)$, its shortest distance to the center of the circle $(xCenter, yCenter)$ is $\sqrt{(x - xCenter)^2 + (y - yCenter)^2}$. If this distance is less than or equal to the radius $radius$, then this point is within the circle (including the boundary).
49+
50+
For points within the rectangle (including the boundary), their x-coordinates $x$ satisfy $x_1 \leq x \leq x_2$, and their y-coordinates $y$ satisfy $y_1 \leq y \leq y_2$. To determine whether the circle and rectangle overlap, we need to find a point $(x, y)$ within the rectangle such that $a = |x - xCenter|$ and $b = |y - yCenter|$ are minimized. If $a^2 + b^2 \leq radius^2$, then the circle and rectangle overlap.
51+
52+
Therefore, the problem is transformed into finding the minimum value of $a = |x - xCenter|$ when $x \in [x_1, x_2]$, and the minimum value of $b = |y - yCenter|$ when $y \in [y_1, y_2]$.
53+
54+
For $x \in [x_1, x_2]$:
55+
56+
- If $x_1 \leq xCenter \leq x_2$, then the minimum value of $|x - xCenter|$ is $0$;
57+
- If $xCenter < x_1$, then the minimum value of $|x - xCenter|$ is $x_1 - xCenter$;
58+
- If $xCenter > x_2$, then the minimum value of $|x - xCenter|$ is $xCenter - x_2$.
59+
60+
Similarly, we can find the minimum value of $|y - yCenter|$ when $y \in [y_1, y_2]$. We can use a function $f(i, j, k)$ to handle the above situations.
61+
62+
That is, $a = f(x_1, x_2, xCenter)$, $b = f(y_1, y_2, yCenter)$. If $a^2 + b^2 \leq radius^2$, then the circle and rectangle overlap.
63+
4664
<!-- tabs:start -->
4765

4866
### **Python3**

solution/1400-1499/1402.Reducing Dishes/README_EN.md

+12
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,18 @@ Each dish is prepared in one unit of time.</pre>
4848

4949
## Solutions
5050

51+
**Solution 1: Greedy + Sorting**
52+
53+
Suppose we only choose one dish, then we should choose the dish with the highest satisfaction $s_0$, and check whether $s_0$ is greater than 0. If $s_0 \leq 0$, then we don't cook any dishes, otherwise, we cook this dish, and the total satisfaction is $s_0$.
54+
55+
If we choose two dishes, then we should choose the two dishes with the highest satisfaction $s_0$ and $s_1$, and the satisfaction is $s_1 + 2 \times s_0$. At this time, we need to ensure that the satisfaction after the selection is greater than the satisfaction before the selection, that is, $s_1 + 2 \times s_0 > s_0$, which means as long as $s_1 + s_0 > 0$, we can choose these two dishes.
56+
57+
By analogy, we can find a rule, that is, we should choose the $k$ dishes with the highest satisfaction, and ensure that the sum of the satisfaction of the first $k$ dishes is greater than $0$.
58+
59+
In implementation, we can first sort the satisfaction of all dishes, and then start choosing from the dish with the highest satisfaction. Each time we add the satisfaction of the current dish, if the result of the addition is less than or equal to $0$, then we no longer choose the dishes behind, otherwise, we choose this dish.
60+
61+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array.
62+
5163
<!-- tabs:start -->
5264

5365
### **Python3**

solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@
3737

3838
## Solutions
3939

40+
**Solution 1: Sorting**
41+
42+
We can first sort the array $nums$ in descending order, then add the elements to the array from largest to smallest. After each addition, we check whether the sum of the current elements is greater than the sum of the remaining elements. If it is, we return the current array.
43+
44+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$.
45+
4046
<!-- tabs:start -->
4147

4248
### **Python3**

solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ Step 1) 2 是偶数,除 2 得到 1
6464

6565
**方法一:模拟操作**
6666

67-
模拟操作 1/2,同时用 carry 记录进位。
67+
我们模拟操作 $1$ 和 $2$,同时用 carry 记录进位。
68+
69+
时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。
6870

6971
<!-- tabs:start -->
7072

solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md

+6
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ Step 1) 2 is even, divide by 2 and obtain 1.&nbsp;
5959

6060
## Solutions
6161

62+
**Solution 1: Simulation**
63+
64+
We simulate operations $1$ and $2$, while using `carry` to record the carry-over.
65+
66+
The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
67+
6268
<!-- tabs:start -->
6369

6470
### **Python3**

solution/1400-1499/1405.Longest Happy String/README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@
5252

5353
<!-- 这里可写通用的实现逻辑 -->
5454

55-
贪心,优先选择剩余最多的字符,通过优先队列或排序,确保每次选到的字符都是剩余最多的(为了避免出现连续 3 个一样的字符,一些情况需要选择剩余第二多的字符)
55+
**方法一:贪心 + 优先队列**
56+
57+
贪心,优先选择剩余最多的字符,通过优先队列或排序,确保每次选到的字符都是剩余最多的(为了避免出现连续 3 个一样的字符,一些情况需要选择剩余第二多的字符)。
5658

5759
<!-- tabs:start -->
5860

solution/1400-1499/1405.Longest Happy String/README_EN.md

+4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545

4646
## Solutions
4747

48+
**Solution 1: Greedy + Priority Queue**
49+
50+
The greedy strategy is to prioritize the selection of characters with the most remaining occurrences. By using a priority queue or sorting, we ensure that the character selected each time is the one with the most remaining occurrences (to avoid having three consecutive identical characters, in some cases, we need to select the character with the second most remaining occurrences).
51+
4852
<!-- tabs:start -->
4953

5054
### **Python3**

solution/1400-1499/1406.Stone Game III/README_EN.md

+17
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ Remember that both play optimally so here Alice will choose the scenario that ma
5454

5555
## Solutions
5656

57+
**Solution 1: Memoization Search**
58+
59+
We design a function $dfs(i)$, which represents the maximum score difference that the current player can obtain when playing the game in the range $[i, n)$. If $dfs(0) > 0$, it means that the first player Alice can win; if $dfs(0) < 0$, it means that the second player Bob can win; otherwise, it means that the two players tie.
60+
61+
The execution logic of the function $dfs(i)$ is as follows:
62+
63+
- If $i \geq n$, it means that there are no stones to take now, so we can directly return $0$;
64+
- Otherwise, we enumerate that the current player takes the first $j+1$ piles of stones, where $j \in \{0, 1, 2\}$. Then the score difference that the other player can get in the next round is $dfs(i + j + 1)$, so the score difference that the current player can get is $\sum_{k=i}^{i+j} stoneValue[k] - dfs(i + j + 1)$. We want to maximize the score difference of the current player, so we can use the $\max$ function to get the maximum score difference, that is:
65+
66+
$$
67+
dfs(i) = \max_{j \in \{0, 1, 2\}} \left\{\sum_{k=i}^{i+j} stoneValue[k] - dfs(i + j + 1)\right\}
68+
$$
69+
70+
To prevent repeated calculations, we can use memoization search.
71+
72+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of piles of stones.
73+
5774
<!-- tabs:start -->
5875

5976
### **Python3**

0 commit comments

Comments
 (0)