【Lintcode】1338. Parking Dilemma

题目地址:

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 ba+1。题目保证 k k k小于等于 A A A的长度。

先排序,然后求最大的 A [ i + k − 1 ] − A [ i ] + 1 A[i+k-1]-A[i]+1 A[i+k1]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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值