LeetCode -- 853. 车队
我们根据position进行排序,然后倒序遍历。若后一辆车的时间比前一个少,前一辆车永远也追不上后一个,res ++ ;否则,前一辆车的时间等于后一个。
class Solution { struct Node { int p, s; double ti; bool operator < (const Node &w) const { return this -> p < w.p; } void operator = (const Node &w) { this -> p = w.p; this -> s = w.s; this -> ti = w.ti; } }; public: int carFleet(int target, vector<int>& position, vector<int>& speed) { int res = 0; int n = position.size(); vector<Node> tm(n); for(int i = 0; i < n; i ++ ) { tm[i].p = position[i]; tm[i].s = speed[i]; tm[i].ti = 1.0 * (target - position[i]) / speed[i]; } sort(tm.begin(), tm.end()); for(int i = n - 1; i; i -- ) { if(tm[i].ti < tm[i - 1].ti) res ++ ; else tm[i - 1] = tm[i]; } return res + 1; } };
java class Solution { class Node { public int p, s; public double ti; Node(int p, int s) { this.p = p; this.s = s; } }; public int carFleet(int target, int[] position, int[] speed) { int n = position.length; Node[] cars = new Node[n]; for(int i = 0; i < n; i ++ ) { cars[i] = new Node(position[i], speed[i]); cars[i].ti = (double)(target - position[i]) / speed[i]; } Arrays.sort(cars, (a, b) -> Integer.compare(a.p, b.p)); int res = 0; for(int i = n - 1; i > 0; i -- ) { if(cars[i].ti < cars[i - 1].ti) res ++ ; else cars[i - 1] = cars[i]; } return res + 1; } }
python class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: n = len(position) cars = sorted(zip(position, speed)) times = [float(target - p) / s for p, s in cars] res = 0 for i in range(n - 1, -1, -1): if times[i] < times[i - 1]: res += 1 else: times[i - 1] = times[i] return res + 1
js /** * @param {number} target * @param {number[]} position * @param {number[]} speed * @return {number} */ var carFleet = function(target, position, speed) { let n = position.length let cars = position.map((v, i) => { return [v, (target - v) / speed[i]]; }); cars.sort((a, b) => { return a[0] - b[0]; }); let res = 0; for(let i = n - 1; i > 0; i -- ) { if(cars[i][1] < cars[i - 1][1]) res ++ ; else cars[i - 1] = cars[i]; } return res + 1; };
golang type Node struct { p int s int ti float64 } func carFleet(target int, position []int, speed []int) int { n := len(position) cars := make([] Node, n) for i := 0; i < n; i ++ { cars[i].p = position[i] cars[i].s = speed[i] cars[i].ti = float64(target - position[i]) / float64(speed[i]) } sort.Slice(cars, func(i int, j int) bool { return cars[i].p < cars[j].p }); res := 0 for i := n - 1; i > 0; i -- { if cars[i].ti < cars[i - 1].ti { res ++ } else { cars[i - 1].ti = cars[i].ti } } return res + 1 }