题目链接
很直观的题目,我们只需要把所有的car按照离target的距离从小到大排列,然后依次扫过去看当前的车和前面的fleet的第一辆车能否在到达target之前相遇,可以的话这两车就merge到前面的fleet。否则这辆车就成为新的fleet的第一辆车。时间复杂度的话就是sorting的时间复杂度O(n * log n),空间复杂度O(n),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int carFleet(int target, vector<int>& position, vector<int>& speed) { | |
int n = position.size(); | |
vector<int> idxs; | |
for(int i = 0; i < n; ++i)idxs.push_back(i); | |
auto comp = [&](const int& lhs, const int& rhs) | |
{ | |
return position[lhs] > position[rhs]; | |
}; | |
sort(idxs.begin(), idxs.end(), comp); | |
int fleets = 0, i = 0; | |
while(i < n) | |
{ | |
int idx = idxs[i], j = i + 1; | |
long pos = position[idx], spd = speed[idx]; | |
//(target - pos[idxs[j]]) / speed[idxs[j]] <= (target - pos[idxs[i]]) / speed[idxs[i]] | |
while(j < n && (target - position[idxs[j]]) * spd <= (target - pos) * speed[idxs[j]])++j; | |
++fleets; | |
i = j; | |
} | |
return fleets; | |
} | |
}; |
No comments:
Post a Comment