题目地址:
https://www.lintcode.com/problem/parking-dilemma/description
给定一个数组 A A A,再给定正整数 k k k,求最短的闭区间 [ a , b ] [a,b] [a,b]使得其能包含 A A A的至少 k k k个数,返回这个区间的 b − a + 1 b-a+1 b−a+1。题目保证 k k k小于等于 A A A的长度。
先排序,然后求最大的 A [ i + k − 1 ] − A [ i ] + 1 A[i+k-1]-A[i]+1 A[i+k−1]−A[i]+1即可。代码如下:
import java.util.Arrays;
public class Solution {
/**
* @param cars: integer array of length denoting the parking slots where cars are parked
* @param k: integer denoting the number of cars that have to be covered by the roof
* @return: return the minium length of the roof that would cover k cars
*/
public int ParkingDilemma(int[] cars, int k) {
// write your code here
Arrays.sort(cars);
int res = cars[cars.length - 1] - cars[0] + 1;
for (int i = 0; i + k - 1 < cars.length; i++) {
res = Math.min(res, cars[i + k - 1] - cars[i] + 1);
}
return res;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn), n n n是数字个数,空间 O ( 1 ) O(1) O(1)。