无限路上形成的预期汽车集群数
给定一个大小为N的数组speed[] ,表示N辆汽车在无限长的单车道道路上从左到右行驶的速度(即不允许超车)。最初,最右边的汽车位于第一个位置,每当一辆速度较高的汽车到达一辆速度较低的汽车时,它们就会开始以速度移动到较慢的汽车并形成一个集群。任务是找出将形成的集群的总数。
注意:单车也被视为一个集群。
例子:
Input: speed[] = {1, 4, 5, 2, 17, 4 }
Output: 3
Explanation: After a certain time, car with speed 17 will reach car with speed 4(car5) and will form a cluster.
And similarly, cars with speed 4 and 5 will start moving with speed 2 on reaching car3.
The clusters will be (car0), (car1, car2, car3), (car4, car5).
Input: speed[] = {2, 3, 4, 7, 7}
Output: 5
Explanation: Each car will form a cluster.
方法: 该解决方案基于贪婪方法。在这里,速度较慢的汽车与后面的所有汽车形成一个集群,并且速度大于自身。请按照以下步骤解决问题:
- 从数组 speed[] 的最后一个索引开始迭代。
- 将汽车的速度存储在一个变量中,比如currentCar 。
- 直到currentCar后面的汽车的速度大于它自己时,才会形成一个集群。因此,一旦发现后面有一辆速度较慢的汽车或数组超出范围,就立即增加集群的值。
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
#include
using namespace std;
// Function to count total number of clusters
int countClusters(vector& speed)
{
int N = speed.size();
// For number of clusters
int cluster = 0;
for (int i = N - 1; i >= 0; i--) {
int currentCar = speed[i];
// comparing with previous car
while (i != 0 and speed[i - 1]
> currentCar) {
i--;
}
cluster++;
}
return cluster;
}
// Driver code
int main()
{
vector speed = { 1, 4, 5, 2, 17, 4 };
int clusters = countClusters(speed);
cout << clusters;
return 0;
}
Java
// Java program to implement
// the above approach
class GFG
{
// Function to count total number of clusters
static int countClusters(int []speed)
{
int N = speed.length;
// For number of clusters
int cluster = 0;
for (int i = N - 1; i >= 0; i--) {
int currentCar = speed[i];
// comparing with previous car
while (i != 0 && speed[i - 1]
> currentCar) {
i--;
}
cluster++;
}
return cluster;
}
// Driver Code
public static void main(String args[])
{
int []speed = { 1, 4, 5, 2, 17, 4 };
int clusters = countClusters(speed);
System.out.println(clusters);
}
}
// This code is contributed by Saurabh Jaiswal
Python3
# Python code to implement above approach
# Function to count total number of clusters
def countClusters(speed):
N = len(speed)
clusters = 0
i = N-1
while(i >= 0):
currentCar = speed[i]
while(i != 0 and speed[i-1] > currentCar):
i = i-1
clusters = clusters+1
i = i-1
return clusters
# Driver code
if __name__ == '__main__':
speed = [1, 4, 5, 2, 17, 4]
clusters = countClusters(speed)
print(clusters)
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to count total number of clusters
static int countClusters(int []speed)
{
int N = speed.Length;
// For number of clusters
int cluster = 0;
for (int i = N - 1; i >= 0; i--) {
int currentCar = speed[i];
// comparing with previous car
while (i != 0 && speed[i - 1]
> currentCar) {
i--;
}
cluster++;
}
return cluster;
}
// Driver Code
public static void Main()
{
int []speed = { 1, 4, 5, 2, 17, 4 };
int clusters = countClusters(speed);
Console.Write(clusters);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
3
时间复杂度: O(N)
辅助空间: O(1)