题目地址:
https://leetcode.com/problems/car-fleet/
数轴上有 n n n辆车,每辆车都在向右行使,目的地是 x x x。给出每辆车的位置和其速度。当一辆车在到达目的地或者之前赶上了另一辆车的时候,它们就会结合起来成为一个“车队”,并且按照离目的地近的那辆车的速度一同行驶。问到达终点的时候一共有多少个不同车队。
先将车按其位置从左到右排序,一开始假设有 n n n个车队,思路是每次某个车追上了另一个车(或者车队),则让答案减 1 1 1。维护一个变量 c c c,是当前车右边的车(或车队)到达目的地需要的时间,然后从后向前遍历,如果当前的车能够在到达目的地或更早的位置追上其前面的车队(对应的是花的时间一样或者更短),则说明该车要加入其后面的车队,答案减 1 1 1;否则说明该车自己形成新的车队,则更新 c c c为其到达目的地需要的时间。代码如下:
class Solution {
public:
int carFleet(int t, vector<int>& pos, vector<int>& speed) {
int n = pos.size();
vector<int> id;
for (int i = 0; i < n; i++) id.push_back(i);
sort(id.begin(), id.end(), [&](int x, int y) { return pos[x] < pos[y]; });
int res = n;
double last = 0;
for (int i = n - 1; i >= 0; i--) {
int idx = id[i];
double time = (double)(t - pos[idx]) / speed[idx];
if (time <= last)
res--;
else
last = time;
}
return res;
}
};
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( n ) O(n) O(n)。