Open Zheaoli opened 2 years ago
/*
* @lc app=leetcode id=853 lang=typescript
*
* [853] Car Fleet
*/
// @lc code=start
function carFleet(target: number, position: number[], speed: number[]): number {
const carList = [] as [number, number][];
const ansStack = [] as number[];
// store [position, speed] pairs
position.forEach((p, i) => carList.push([p, speed[i]]));
// sorted by poisiton
carList.sort((a, b) => a[0] - b[0]);
for (let i = carList.length - 1; i >= 0; i--) {
const [position, speed] = carList[i];
const timeToTarget = (target - position) / speed;
ansStack.push(timeToTarget);
// if current car's time to the target is quicker than the last one
// then we need to pop
if (ansStack.length >= 2 && ansStack[ansStack.length - 2] >= timeToTarget) {
ansStack.pop();
}
}
return ansStack.length;
};
// @lc code=end
微信id: 弘树 来自 vscode 插件
2022-09-24