题目:
/** 单调栈:存储到终点的时间,需要考虑浮点数* 思路:首先按照距离进行排序(目的:如果离终点远的车辆用时比前面的车辆用时短,则是一个车队)* 排序后计算每一辆车辆的时间如果用时比栈顶的时间短,说明是一个车队的,否则不是入栈。* @auther start* @create 2023-12-06 19:23*/
public class L853 {public int carFleet(int target, int[] position, int[] speed) {int n = position.length;Car[] cars = new Car[n];for (int i = 0; i < n; i++) {cars[i] = new Car(position[i], speed[i]);}//排序,降序排序,使用lamda表达式Arrays.sort(cars, (a, b) -> a.pos - b.pos > 0 ? -1 : 1);Deque<Double> stack = new LinkedList<>();for (int i = 0; i < n; i++) {double t = (target - cars[i].pos) * 1.0 / cars[i].speed;if (!stack.isEmpty() && stack.peek() >= t) {//该车辆追上了栈顶元素代表的车辆,整合,最后栈中的个数就是车队的数量} else {stack.push(t);}}return stack.size();}static class Car {int pos = 0, speed = 0;public Car(int pos, int speed) {this.pos = pos;this.speed = speed;}}}