inteliminateMaximum(int* dist, int distSize, int* speed, int speedSize) { int n = distSize; int arrivalTimes[n]; for (int i = 0; i < n; i++) { arrivalTimes[i] = (dist[i] - 1) / speed[i] + 1; } qsort(arrivalTimes, n, sizeof(int), cmp); for (int i = 0; i < n; i++) { if (arrivalTimes[i] <= i) { return i; } } return n; }
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funceliminateMaximum(dist []int, speed []int)int { n := len(dist); arrivalTimes := make([]int, n) for i := 0; i < n; i++ { arrivalTimes[i] = (dist[i] - 1) / speed[i] + 1 } sort.Ints(arrivalTimes) for i := 0; i < n; i++ { if arrivalTimes[i] <= i { return i } } return n }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var eliminateMaximum = function(dist, speed) { const n = dist.length; const arrivalTimes = newArray(n).fill(0); for (let i = 0; i < n; i++) { arrivalTimes[i] = Math.ceil(dist[i] / speed[i]); } arrivalTimes.sort((a, b) => a - b); for (let i = 0; i < n; i++) { if (arrivalTimes[i] <= i) { return i; } } return n; };
复杂度分析
时间复杂度:O(n \times \log n),其中 n 是数组 dist 和 speed 的长度。为排序的时间复杂度。