mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 07:54:07 +00:00
day 34: 853-car-fleet
This commit is contained in:
parent
024fb6466a
commit
2e3c839ec5
12
853-car-fleet/driver.cpp
Normal file
12
853-car-fleet/driver.cpp
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
#include "soln.hpp"
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
int target = 12;
|
||||||
|
vector<int> position{10, 8, 0, 5, 3};
|
||||||
|
vector<int> speed{2, 4, 1, 1, 3};
|
||||||
|
int answer = 3;
|
||||||
|
Solution soln;
|
||||||
|
cout << "Found car fleets correctly? " << soln.test(target, position, speed, answer) << endl;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
35
853-car-fleet/soln.cpp
Normal file
35
853-car-fleet/soln.cpp
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#include "soln.hpp"
|
||||||
|
|
||||||
|
int Solution::carFleet(int target, vector<int> &position, vector<int> &speed)
|
||||||
|
{
|
||||||
|
if (position.size() < 2)
|
||||||
|
return position.size();
|
||||||
|
// int fleets = position.size();
|
||||||
|
vector<Car> cars;
|
||||||
|
vector<double> slowest_times;
|
||||||
|
for (int i = 0; i < position.size(); i++)
|
||||||
|
{
|
||||||
|
cars.push_back(Car(position[i], speed[i]));
|
||||||
|
}
|
||||||
|
sort(
|
||||||
|
cars.begin(),
|
||||||
|
cars.end(),
|
||||||
|
[](const Car &lhs, const Car &rhs)
|
||||||
|
{
|
||||||
|
return lhs.start_pos < rhs.start_pos;
|
||||||
|
});
|
||||||
|
for (int i = cars.size() - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
slowest_times.push_back((target - cars[i].start_pos) / float(cars[i].car_speed));
|
||||||
|
if (slowest_times.size() >= 2 && slowest_times[slowest_times.size() - 1] <= slowest_times[slowest_times.size() - 2])
|
||||||
|
{
|
||||||
|
slowest_times.pop_back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slowest_times.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Solution::test(int target, vector<int> &position, vector<int> &speed, int answer)
|
||||||
|
{
|
||||||
|
return carFleet(target, position, speed) == answer;
|
||||||
|
}
|
||||||
15
853-car-fleet/soln.hpp
Normal file
15
853-car-fleet/soln.hpp
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
#include <bits/stdc++.h>
|
||||||
|
using namespace std;
|
||||||
|
class Solution
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
struct Car
|
||||||
|
{
|
||||||
|
int start_pos;
|
||||||
|
double car_speed;
|
||||||
|
Car() : start_pos(0), car_speed(0) {}
|
||||||
|
Car(int pos, double s) : start_pos(pos), car_speed(s) {}
|
||||||
|
};
|
||||||
|
int carFleet(int target, vector<int> &position, vector<int> &speed);
|
||||||
|
bool test(int target, vector<int> &position, vector<int> &speed, int answer);
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user