1094. Car Pooling (M)
https://leetcode.com/problems/car-pooling/
There is a car with capacity
empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity
and an array trips
where trip[i] = [numPassengersi, fromi, toi]
indicates that the ith
trip has numPassengersi
passengers and the locations to pick them up and drop them off are fromi
and toi
respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true
if it is possible to pick up and drop off all passengers for all the given trips, or false
otherwise.
Example 1:
Example 2:
Constraints:
1 <= trips.length <= 1000
trips[i].length == 3
1 <= numPassengersi <= 100
0 <= fromi < toi <= 1000
1 <= capacity <= 105
Solution:
Solution:
你是一个开公交车的司机,公交车的最大载客量为 capacity
,沿途要经过若干车站,给你一份乘客行程表 int[][] trips
,其中 trips[i] = [num, start, end]
代表着有 num
个旅客要从站点 start
上车,到站点 end
下车,请你计算是否能够一次把所有旅客运送完毕(不能超过最大载客量 capacity
)。
函数签名如下:
比如输入:
这就不能一次运完,因为 trips[1]
最多只能上 2 人,否则车就会超载。
相信你已经能够联想到差分数组技巧了:trips[i]
代表着一组区间操作,旅客的上车和下车就相当于数组的区间加减;只要结果数组中的元素都小于 capacity
,就说明可以不超载运输所有旅客。
但问题是,差分数组的长度(车站的个数)应该是多少呢?题目没有直接给,但给出了数据取值范围:
车站个数最多为 1000,那么我们的差分数组长度可以直接设置为 1001:
至此,这道题也解决了。
最后,差分数组和前缀和数组都是比较常见且巧妙的算法技巧,分别适用不同的常见,而且是会者不难,难者不会。所以,关于差分数组的使用,你学会了吗?
Last updated