Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add solutions to lc problems: No.1385+ #2159

Merged
merged 1 commit into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ For arr1[2]=8 we have:

## Solutions

**Solution 1: Sorting + Binary Search**

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.

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.

<!-- tabs:start -->

### **Python3**
Expand Down
14 changes: 14 additions & 0 deletions solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,20 @@

## Solutions

**Solution 1: Hash Table + Bit Manipulation**

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.

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]$.

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$.

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.

After the traversal, we get the final answer.

The time complexity is $O(m)$, and the space complexity is $O(m)$. Where $m$ is the length of $reservedSeats$.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ The fourth number in the sorted array is 7.

## Solutions

**Solution 1: Custom Sorting**

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$.

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.

Finally, we return the $k$-th number after sorting.

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$.

<!-- tabs:start -->

### **Python3**
Expand Down
29 changes: 29 additions & 0 deletions solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,35 @@

## Solutions

**Solution 1: Dynamic Programming**

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.

The proof is as follows:

- When $n = 1$, we can choose any number in the array.
- 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.

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.

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.

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:])$.

The solution method of function $g(nums)$ is as follows:

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$.

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:

$$
f[i][j] = \max(f[i - 1][j], f[i - 2][j - 1] + nums[i - 1])
$$

Finally, return $f[m][n]$.

The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array $slices$.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ nums index target

## Solutions

**Solution 1: Simulation**

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.

The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.

<!-- tabs:start -->

### **Python3**
Expand Down
6 changes: 6 additions & 0 deletions solution/1300-1399/1390.Four Divisors/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ The answer is the sum of divisors of 21 only.

## Solutions

**Solution 1: Factor Decomposition**

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.

The time complexity is $O(n \times \sqrt{n})$, where $n$ is the length of the array. The space complexity is $O(1)$.

<!-- tabs:start -->

### **Python3**
Expand Down
10 changes: 10 additions & 0 deletions solution/1300-1399/1392.Longest Happy Prefix/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@

## Solutions

**Solution 1: String Hashing**

**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.

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.

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.

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.

<!-- tabs:start -->

### **Python3**
Expand Down
4 changes: 4 additions & 0 deletions solution/1300-1399/1393.Capital GainLoss/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$.

## Solutions

**Solution 1: GROUP BY + SUM(IF())**

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.

<!-- tabs:start -->

### **SQL**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@

## Solutions

**Solution 1: Counting**

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$.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of $arr$.

<!-- tabs:start -->

### **Python3**
Expand Down
12 changes: 12 additions & 0 deletions solution/1300-1399/1395.Count Number of Teams/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@

## Solutions

**Solution 1: Enumerate Middle Element**

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.

The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Where $n$ is the length of the array $rating$.

**Solution 2: Binary Indexed Tree**

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.

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$.

<!-- tabs:start -->

### **Python3**
Expand Down
15 changes: 15 additions & 0 deletions solution/1300-1399/1396.Design Underground System/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,21 @@ undergroundSystem.getAverageTime(&quot;Leyton&quot;, &quot;Paradise&quot;); // r

## Solutions

**Solution 1: Hash Table**

We use two hash tables to store data:

- `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)`.
- `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)`.

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)`.

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`.

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$.

The time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is the number of passengers.

<!-- tabs:start -->

### **Python3**
Expand Down
10 changes: 10 additions & 0 deletions solution/1300-1399/1399.Count Largest Group/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ There are 4 groups with largest size.

## Solutions

**Solution 1: Hash Table or Array**

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.

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$.

Finally, we return $ans$.

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$.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ Some possible constructions &quot;anna&quot; + &quot;elble&quot;, &quot;anbna&qu

## Solutions

**Solution 1: Counting**

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`.

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`.

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$.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@

## Solutions

**Solution 1: Mathematics**

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).

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.

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]$.

For $x \in [x_1, x_2]$:

- If $x_1 \leq xCenter \leq x_2$, then the minimum value of $|x - xCenter|$ is $0$;
- If $xCenter < x_1$, then the minimum value of $|x - xCenter|$ is $x_1 - xCenter$;
- If $xCenter > x_2$, then the minimum value of $|x - xCenter|$ is $xCenter - x_2$.

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.

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.

<!-- tabs:start -->

### **Python3**
Expand Down
12 changes: 12 additions & 0 deletions solution/1400-1499/1402.Reducing Dishes/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ Each dish is prepared in one unit of time.</pre>

## Solutions

**Solution 1: Greedy + Sorting**

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$.

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.

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$.

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.

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.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@

## Solutions

**Solution 1: Sorting**

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.

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$.

<!-- tabs:start -->

### **Python3**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ Step 1) 2 是偶数,除 2 得到 1

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

模拟操作 1/2,同时用 carry 记录进位。
我们模拟操作 $1$ 和 $2$,同时用 carry 记录进位。

时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。

<!-- tabs:start -->

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ Step 1) 2 is even, divide by 2 and obtain 1.&nbsp;

## Solutions

**Solution 1: Simulation**

We simulate operations $1$ and $2$, while using `carry` to record the carry-over.

The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.

<!-- tabs:start -->

### **Python3**
Expand Down
4 changes: 3 additions & 1 deletion solution/1400-1499/1405.Longest Happy String/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@

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

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

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

<!-- tabs:start -->

Expand Down
4 changes: 4 additions & 0 deletions solution/1400-1499/1405.Longest Happy String/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@

## Solutions

**Solution 1: Greedy + Priority Queue**

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).

<!-- tabs:start -->

### **Python3**
Expand Down
17 changes: 17 additions & 0 deletions solution/1400-1499/1406.Stone Game III/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ Remember that both play optimally so here Alice will choose the scenario that ma

## Solutions

**Solution 1: Memoization Search**

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.

The execution logic of the function $dfs(i)$ is as follows:

- If $i \geq n$, it means that there are no stones to take now, so we can directly return $0$;
- 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:

$$
dfs(i) = \max_{j \in \{0, 1, 2\}} \left\{\sum_{k=i}^{i+j} stoneValue[k] - dfs(i + j + 1)\right\}
$$

To prevent repeated calculations, we can use memoization search.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of piles of stones.

<!-- tabs:start -->

### **Python3**
Expand Down
Loading