-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
44 lines (37 loc) · 1.27 KB
/
Copy pathMain.java
File metadata and controls
44 lines (37 loc) · 1.27 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
// LeetCode Problem: https://leetcode.com/problems/car-fleet/
import java.util.Arrays;
import java.util.Stack;
class Solution {
class Pair {
public int first, second;
public Pair(int first, int second){
this.first = first;
this.second = second;
}
}
public int carFleet(int target, int[] position, int[] speed) {
Stack<Double> st = new Stack<>();
Pair[] carSpeed = new Pair[position.length];
for(int i =0; i<position.length; i++){
carSpeed[i] = new Pair(position[i], speed[i]);
}
Arrays.sort(carSpeed, (a, b) -> b.first - a.first);
for(int i=0; i<carSpeed.length; i++){
double time = (double)(target - carSpeed[i].first) / (double) (carSpeed[i].second);
if(!st.isEmpty() && time <= st.peek())
continue;
st.push(time);
}
return st.size();
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int target = 12;
int[] position = {10, 8, 0, 5, 3};
int[] speed = {2, 4, 1, 1, 3};
int result = solution.carFleet(target, position, speed);
System.out.println("Number of car fleets: " + result);
}
}