N Car Fleet

public class Solution {
    /**
     * @param target: the target
     * @param position: the initial position
     * @param speed: the speed
     * @return: How many car fleets will arrive at the destination
     */
		public int carFleet(int target, int[] position, int[] speed) {
			int n = position.length;
			int[][] cars = new int[n][2];
			for (int i = 0; i < n; i++) {
				cars[i][0] = position[i];
				cars[i][1] = speed[i];                            //双属性合并的套路
			}
			Arrays.sort(cars, (a, b) -> (b[0] - a[0])); //对比数组中的第一个数
			int res = 0;
			double maxTime = 0;
			for (int i = 0; i < n; i++) {
				double time = (double)(target - cars[i][0]) / cars[i][1];
				if (time > maxTime) {
					maxTime = time;
					res++;
				}
			}
			return res;
		}
}

最后更新于

这有帮助吗?