Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add solutions to lc problems #2026

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

Merged
acbin merged 1 commit into main from dev
Nov 28, 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
63 changes: 58 additions & 5 deletions solution/1000-1099/1094.Car Pooling/README.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@

**方法一:差分数组**

我们可以利用差分数组的思想,将每个行程的乘客数加到起点,减去终点,最后遍历差分数组,若当前乘客数大于容量,则返回 `false`,否则返回 `true`
我们可以利用差分数组的思想,将每个行程的乘客数加到起点,减去终点,最后我们只需要判断差分数组的前缀和是否都不大于车的最大载客量即可

时间复杂度 $O(n),ドル空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为行程数和行程中的最大终点
时间复杂度 $O(n),ドル空间复杂度 $O(M)$。其中 $n$ 是行程数,而 $M$ 是行程中最大的终点,本题中 $M \le 1000$

<!-- tabs:start -->

Expand All @@ -59,7 +59,8 @@
```python
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = [0] * 1001
mx = max(e[2] for e in trips)
d = [0] * (mx + 1)
for x, f, t in trips:
d[f] += x
d[t] -= x
Expand Down Expand Up @@ -145,7 +146,8 @@ func carPooling(trips [][]int, capacity int) bool {
* @return {boolean}
*/
var carPooling = function (trips, capacity) {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand All @@ -165,7 +167,8 @@ var carPooling = function (trips, capacity) {

```ts
function carPooling(trips: number[][], capacity: number): boolean {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand All @@ -181,6 +184,56 @@ function carPooling(trips: number[][], capacity: number): boolean {
}
```

### **C#**

```cs
public class Solution {
public bool CarPooling(int[][] trips, int capacity) {
int mx = trips.Max(x => x[2]);
int[] d = new int[mx + 1];
foreach (var trip in trips) {
int x = trip[0], f = trip[1], t = trip[2];
d[f] += x;
d[t] -= x;
}
int s = 0;
foreach (var x in d) {
s += x;
if (s > capacity) {
return false;
}
}
return true;
}
}
```

### **Rust**

```rust
impl Solution {
pub fn car_pooling(trips: Vec<Vec<i32>>, capacity: i32) -> bool {
let mx = trips
.iter()
.map(|e| e[2])
.max()
.unwrap_or(0) as usize;
let mut d = vec![0; mx + 1];
for trip in &trips {
let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize);
d[f] += x;
d[t] -= x;
}
d.iter()
.scan(0, |acc, &x| {
*acc += x;
Some(*acc)
})
.all(|s| s <= capacity)
}
}
```

### **...**

```
Expand Down
65 changes: 62 additions & 3 deletions solution/1000-1099/1094.Car Pooling/README_EN.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,21 @@

## Solutions

**Solution 1: Difference Array**

We can use the idea of a difference array, adding the number of passengers to the starting point of each trip and subtracting from the end point. Finally, we just need to check whether the prefix sum of the difference array does not exceed the maximum passenger capacity of the car.

The time complexity is $O(n),ドル and the space complexity is $O(M)$. Here, $n$ is the number of trips, and $M$ is the maximum end point in the trips. In this problem, $M \le 1000$.

<!-- tabs:start -->

### **Python3**

```python
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = [0] * 1001
mx = max(e[2] for e in trips)
d = [0] * (mx + 1)
for x, f, t in trips:
d[f] += x
d[t] -= x
Expand Down Expand Up @@ -129,7 +136,8 @@ func carPooling(trips [][]int, capacity int) bool {
* @return {boolean}
*/
var carPooling = function (trips, capacity) {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand All @@ -149,7 +157,8 @@ var carPooling = function (trips, capacity) {

```ts
function carPooling(trips: number[][], capacity: number): boolean {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand All @@ -165,6 +174,56 @@ function carPooling(trips: number[][], capacity: number): boolean {
}
```

### **C#**

```cs
public class Solution {
public bool CarPooling(int[][] trips, int capacity) {
int mx = trips.Max(x => x[2]);
int[] d = new int[mx + 1];
foreach (var trip in trips) {
int x = trip[0], f = trip[1], t = trip[2];
d[f] += x;
d[t] -= x;
}
int s = 0;
foreach (var x in d) {
s += x;
if (s > capacity) {
return false;
}
}
return true;
}
}
```

### **Rust**

```rust
impl Solution {
pub fn car_pooling(trips: Vec<Vec<i32>>, capacity: i32) -> bool {
let mx = trips
.iter()
.map(|e| e[2])
.max()
.unwrap_or(0) as usize;
let mut d = vec![0; mx + 1];
for trip in &trips {
let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize);
d[f] += x;
d[t] -= x;
}
d.iter()
.scan(0, |acc, &x| {
*acc += x;
Some(*acc)
})
.all(|s| s <= capacity)
}
}
```

### **...**

```
Expand Down
19 changes: 19 additions & 0 deletions solution/1000-1099/1094.Car Pooling/Solution.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Solution {
public bool CarPooling(int[][] trips, int capacity) {
int mx = trips.Max(x => x[2]);
int[] d = new int[mx + 1];
foreach (var trip in trips) {
int x = trip[0], f = trip[1], t = trip[2];
d[f] += x;
d[t] -= x;
}
int s = 0;
foreach (var x in d) {
s += x;
if (s > capacity) {
return false;
}
}
return true;
}
}
3 changes: 2 additions & 1 deletion solution/1000-1099/1094.Car Pooling/Solution.go
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
func carPooling(trips [][]int, capacity int) bool {
d := [1001]int{}
mx := slices.Max(trips, func(i int) int { return trips[i][2] })
d := make([]int, mx+1)
for _, trip := range trips {
x, f, t := trip[0], trip[1], trip[2]
d[f] += x
Expand Down
3 changes: 2 additions & 1 deletion solution/1000-1099/1094.Car Pooling/Solution.js
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* @return {boolean}
*/
var carPooling = function (trips, capacity) {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand Down
3 changes: 2 additions & 1 deletion solution/1000-1099/1094.Car Pooling/Solution.py
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
d = [0] * 1001
mx = max(e[2] for e in trips)
d = [0] * (mx + 1)
for x, f, t in trips:
d[f] += x
d[t] -= x
Expand Down
21 changes: 21 additions & 0 deletions solution/1000-1099/1094.Car Pooling/Solution.rs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
impl Solution {
pub fn car_pooling(trips: Vec<Vec<i32>>, capacity: i32) -> bool {
let mx = trips
.iter()
.map(|e| e[2])
.max()
.unwrap_or(0) as usize;
let mut d = vec![0; mx + 1];
for trip in &trips {
let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize);
d[f] += x;
d[t] -= x;
}
d.iter()
.scan(0, |acc, &x| {
*acc += x;
Some(*acc)
})
.all(|s| s <= capacity)
}
}
3 changes: 2 additions & 1 deletion solution/1000-1099/1094.Car Pooling/Solution.ts
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
function carPooling(trips: number[][], capacity: number): boolean {
const d = new Array(1001).fill(0);
const mx = Math.max(...trips.map(([, , t]) => t));
const d = Array(mx + 1).fill(0);
for (const [x, f, t] of trips) {
d[f] += x;
d[t] -= x;
Expand Down
20 changes: 20 additions & 0 deletions solution/1000-1099/1099.Two Sum Less Than K/README_EN.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,26 @@

## Solutions

**Solution 1: Sorting + Binary Search**

We can first sort the array $nums,ドル and initialize the answer as $-1$.

Next, we enumerate each element $nums[i]$ in the array, and find the maximum $nums[j]$ in the array that satisfies $nums[j] + nums[i] < k$. Here, we can use binary search to speed up the search process. If we find such a $nums[j],ドル then we can update the answer, i.e., $ans = \max(ans, nums[i] + nums[j])$.

After the enumeration ends, return the answer.

The time complexity is $O(n \times \log n),ドル and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$.

**Solution 2: Sorting + Two Pointers**

Similar to Method 1, we can first sort the array $nums,ドル and initialize the answer as $-1$.

Next, we use two pointers $i$ and $j$ to point to the left and right ends of the array, respectively. Each time we judge whether $s = nums[i] + nums[j]$ is less than $k$. If it is less than $k,ドル then we can update the answer, i.e., $ans = \max(ans, s),ドル and move $i$ one step to the right, otherwise move $j$ one step to the left.

After the enumeration ends, return the answer.

The time complexity is $O(n \times \log n),ドル and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$.

<!-- tabs:start -->

### **Python3**
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@

## Solutions

**Solution 1: Two Pointers + Counter**

We observe that all characters are lowercase letters, so there are at most 26ドル$ different characters. Therefore, if $k > 26$ or $k > n,ドル it is impossible to find any substring of length $k$ without repeated characters, and we can directly return 0ドル$.

Next, we use two pointers $j$ and $i$ to maintain a sliding window, where $j$ is the left endpoint of the sliding window, $i$ is the right endpoint of the sliding window, and a counter $cnt$ is used to count the number of occurrences of each character in the sliding window.

We traverse the string $s,ドル each time adding $s[i]$ to the sliding window, i.e., $cnt[s[i]]++$. If at this time $cnt[s[i]] > 1$ or $i - j + 1 > k,ドル then we loop to remove $s[j]$ from the sliding window, i.e., $cnt[s[j]]--,ドル and move $j$ to the right. If after moving $j$ to the right, the window size $i - j + 1$ is exactly equal to $k,ドル it means that the string in the sliding window is a substring that meets the requirements of the problem, and we increment the result by one.

After the traversal ends, we can get the number of all substrings that meet the requirements of the problem.

The time complexity is $O(n),ドル and the space complexity is $O(C)$. Here, $n$ is the length of the string $s,ドル and $C$ is the size of the character set. In this problem, $C = 26$.

<!-- tabs:start -->

### **Python3**
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,13 @@ The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends

## Solutions

Union find.
**Solution 1: Sorting + Union-Find**

We sort all the logs in ascending order by timestamp, then traverse the sorted logs. Using a union-find set, we check whether the two people in the current log are already friends. If they are not friends, we merge them into one friend circle, until everyone is in one friend circle, then return the timestamp of the current log.

If we have traversed all the logs and not everyone is in one friend circle, then return $-1$.

The time complexity is $O(n \times \log n),ドル and the space complexity is $O(n)$. Here, $n$ is the number of logs.

<!-- tabs:start -->

Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@

## Solutions

**Solution 1: Sorting + Union-Find**

First, we construct a triplet $(v, i, j)$ for each element in the matrix, where $v$ represents the element value, and $i$ and $j$ represent the row and column of the element in the matrix, respectively. Then we sort these triplets in descending order by element value and store them in a list $q$.

Next, we take out the triplets from $q$ in order, use the corresponding element value as the score of the path, and mark the position as visited. Then we check the four adjacent positions (up, down, left, and right) of this position. If an adjacent position has been visited, we merge this position with the current position. If we find that the position $(0, 0)$ and the position $(m - 1, n - 1)$ have been merged, we can directly return the score of the current path as the answer.

The time complexity is $O(m \times n \times (\log (m \times n) + \alpha(m \times n))),ドル where $m$ and $n$ are the number of rows and columns of the matrix, respectively.

<!-- tabs:start -->

### **Python3**
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ On the fourth turn, ans[0] += 4, and the final array is [5,2,3].

## Solutions

**Solution 1: Simulation**

We can directly simulate the process of each person receiving candies, following the rules described in the problem.

The time complexity is $O(\max(\sqrt{candies}, num\_people)),ドル and the space complexity is $O(num\_people)$. Here, $candies$ is the number of candies.

<!-- tabs:start -->

### **Python3**
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@

## Solutions

**Solution 1: Mathematics**

For a complete binary tree, the number of nodes in the $i$th row is 2ドル^{i-1},ドル and the range of node labels in the $i$th row is $[2^{i-1}, 2^i - 1]$. In the problem, for odd-numbered rows, the nodes are labeled from left to right, while for even-numbered rows, the nodes are labeled from right to left. Therefore, for the node $label$ in the $i$th row, its complementary node label is 2ドル^{i-1} + 2^i - 1 - label$. So the actual parent node label of node $label$ is $(2^{i-1} + 2^i - 1 - label) / 2$. We can find the path from the root node to node $label$ by continuously finding the complementary node label and the parent node label until we reach the root node.

Finally, we need to reverse the path, because the problem requires the path from the root node to node $label$.

The time complexity is $O(\log n),ドル where $n$ is the label of the node. Ignoring the space consumption of the answer, the space complexity is $O(1)$.

<!-- tabs:start -->

### **Python3**
Expand Down
Loading

AltStyle によって変換されたページ (->オリジナル) /