-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarfleet.java
More file actions
72 lines (57 loc) · 2.36 KB
/
Copy pathcarfleet.java
File metadata and controls
72 lines (57 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*Car Fleet
Solved
There are n cars traveling to the same destination on a one-lane highway.
You are given two arrays of integers position and speed, both of length n.
position[i] is the position of the ith car (in miles)
speed[i] is the speed of the ith car (in miles per hour)
The destination is at position target miles.
A car can not pass another car ahead of it. It can only catch up to another car and then drive at the same speed as the car ahead of it.
A car fleet is a non-empty set of cars driving at the same position and same speed. A single car is also considered a car fleet.
If a car catches up to a car fleet the moment the fleet reaches the destination, then the car is considered to be part of the fleet.
Return the number of different car fleets that will arrive at the destination.
Example 1:
Input: target = 10, position = [1,4], speed = [3,2]
Output: 1
Explanation: The cars starting at 1 (speed 3) and 4 (speed 2) become a fleet, meeting each other at 10, the destination.
Example 2:
Input: target = 10, position = [4,1,0,7], speed = [2,2,1,1]
Output: 3
Explanation: The cars starting at 4 and 7 become a fleet at position 10. The cars starting at 1 and 0 never catch up to the car ahead of them. Thus, there are 3 car fleets that will arrive at the destination.
Constraints:
n == position.length == speed.length.
1 <= n <= 1000
0 < target <= 1000
0 < speed[i] <= 100
0 <= position[i] < target
All the values of position are unique. */
class Solution {
public int carFleet(int target, int[] position, int[] speed)
{
int [][]nums=new int[position.length][2];
Stack <int[]>stack=new Stack<>();
for(int i=0;i<position.length;i++)
{
nums[i][0]=position[i];
nums[i][1]=speed[i];
}
Arrays.sort(nums, (a, b) -> Integer.compare(b[0], a[0]));
for(int c=0;c<position.length;c++)
{
if(stack.isEmpty())
{
stack.push(nums[c]);
}
else
{
double timeCurrent = (double)(target - nums[c][0]) / nums[c][1];
double timeTop = (double)(target - stack.peek()[0]) / stack.peek()[1];
if (timeCurrent>timeTop)
{
stack.push(nums[c]);
}
}
}
return stack.size();
}
}
//TIME COMPLEXCITY =O(nlogn)