Skip to content

Commit 80413e9

Browse files
Create 1094. 拼车.md
1 parent 7957125 commit 80413e9

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Methodology/1094. 拼车.md

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#### 1094. 拼车
2+
3+
难度:中等
4+
5+
---
6+
7+
车上最初有 `capacity` 个空座位。车  **只能**  向一个方向行驶(也就是说, **不允许掉头或改变方向**
8+
9+
给定整数 `capacity` 和一个数组 `trips` ,  `trip[i] = [numPassengersi, fromi, toi]` 表示第 `i` 次旅行有 `numPassengersi` 乘客,接他们和放他们的位置分别是 `fromi` 和 `toi` 。这些位置是从汽车的初始位置向东的公里数。
10+
11+
当且仅当你可以在所有给定的行程中接送所有乘客时,返回 `true`,否则请返回 `false`
12+
13+
**示例 1:**
14+
15+
```
16+
输入:trips = [[2,1,5],[3,3,7]], capacity = 4
17+
输出:false
18+
```
19+
20+
**示例 2:**
21+
22+
```
23+
输入:trips = [[2,1,5],[3,3,7]], capacity = 5
24+
输出:true
25+
```
26+
27+
**提示:**
28+
29+
* `1 <= trips.length <= 1000`
30+
* `trips[i].length == 3`
31+
* `1 <= numPassengersi <= 100`
32+
* `0 <= fromi < toi <= 1000`
33+
* `1 <= capacity <= 10^5`
34+
35+
---
36+
37+
差分数组:
38+
39+
初始化一个长度为 `1001` 的差分数组,遍历 `trips` 数组并确定最大长度,上车位置处增加 `numPassengers_i` ,下车位置处减少 `numPassengers_i`,再遍历一遍该差分数组,遍历的过程中如果数组和大于 `capacity`,证明超载,返回 `false`,否则遍历完成后返回` true`
40+
41+
```Java
42+
class Solution {
43+
public boolean carPooling(int[][] trips, int capacity) {
44+
int maxLength = 1001;
45+
int[] arrays = new int[maxLength];
46+
for(int i = 0; i < trips.length; i++){
47+
arrays[trips[i][1]] += trips[i][0];
48+
arrays[trips[i][2]] -= trips[i][0];
49+
maxLength = Math.max(maxLength, trips[i][2]);
50+
}
51+
int count = 0;
52+
for(int i = 0; i < maxLength; i++){
53+
count += arrays[i];
54+
if(count > capacity){
55+
return false;
56+
}
57+
}
58+
return true;
59+
}
60+
}
61+
```

0 commit comments

Comments
 (0)