https://leetcode.com/problems/car-fleet/solution/ https://leetcode.com/problems/car-fleet/discuss/139999/Easy-understanding-JAVA-TreeMap-Solution-with-explanation-and-comment N cars are going to the same destination along a one lane road. The destination is target miles away. Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road. A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. The distance between these two cars is ignored - they are assumed to have the same position. A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. ?How many car fleets will arrive at the destination? Example 1: Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 and 8 become a fleet, meeting each other at 12. The car starting at 0 doesn‘t catch up to any other car, so it is a fleet by itself. The cars starting at 5 and 3 become a fleet, meeting each other at 6. Note that no other cars meet these fleets before the destination, so the answer is 3. A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. If one car catch up the one before it, it means the time it takes to reach the target is shorter than the one in front(if no blocking).?For example:?car A at pos a with speed sa?car B at pos b with speed sb?(b < a < target)?Their distances to the target are (target-a) and (target-b).?If (target-a)/sa > (target-b)/sb it means car A take more time to reach target so car B will catch up car A and form a single group. So we use the distance to target as key and speed as value, iterate through all cars in order of their distances to the target.?keep track of currently slowest one(which might block the car behind), if a car can catch up current slowest one, it will not cause a new group.?Otherwise, we count a new group and update the info of slowest class Solution { public int carFleet(int target, int[] position, int[] speed) { TreeMap<Integer, Double> map = new TreeMap<>(); for(int i = 0; i < position.length; i++){ // key : - distance, value : time takes to the target // so the map is ordered by the cloest distance to target // - 10 , -5, -2 map.put(-position[i], (double)(target - position[i]) / speed[i]); } int res = 0; double cur = 0; // the car ahead of it takes cur time to target // pos : a, b .. if a takes more time to reach the target than b does, then a new group is started // and update the new time for this group for(double time : map.values()){ if(time > cur){ cur = time; res++; } } return res; } }
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9929750.html
时间: 2024-10-14 22:06:57