车上最初有 capacity
个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向)
给定整数 capacity
和一个数组 trips
, trip[i] = [numPassengersi, fromi, toi]
表示第 i
次旅行有 numPassengersi
乘客,接他们和放他们的位置分别是 fromi
和 toi
。这些位置是从汽车的初始位置向东的公里数。
当且仅当你可以在所有给定的行程中接送所有乘客时,返回 true
,否则请返回 false
。
示例 1:
输入:trips = [[2,1,5],[3,3,7]], capacity = 4
输出:false
示例 2:
输入:trips = [[2,1,5],[3,3,7]], capacity = 5
输出:true
提示:
1 <= trips.length <= 1000
trips[i].length == 3
1 <= numPassengersi <= 100
0 <= fromi < toi <= 1000
1 <= capacity <= 105
思路:差分数组,对于区间频繁修改的数组
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
int n = 1000;
int[] result = new int[n];
for (int[] trip : trips) {
int numPassengersi = trip[0];
if (numPassengersi > capacity) {
return false;
}
int start = trip[1] - 1;
int end = trip[2] - 1 - 1;
result[start] += numPassengersi;
if (end + 1 < n) {
result[end + 1] -= numPassengersi;
}
}
for (int i = 0; i < 10; i++) {
System.out.print(result[i] + " ");
}
System.out.println();
for (int i = 1; i < n; i++) {
result[i] += result[i - 1];
}
for (int i = 0; i < 10; i++) {
System.out.print(result[i] + " ");
}
System.out.println();
for (int i = 1; i < n; i++) {
if (result[i] > capacity) {
System.out.println(result[i] + " " + capacity);
return false;
}
}
return true;
}
}
//leetcode submit region end(Prohibit modification and deletion)
标签:capacity,numPassengersi,int,System,差分,trips,result,数组,leetcode1094
From: https://blog.51cto.com/u_12550160/6182942