[Leetcode] 683. K Empty Slots 解题报告

题目

There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then.

Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day.

For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N.

Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.

If there isn't such day, output -1.

Example 1:

Input: 
flowers: [1,3,2]
k: 1
Output: 2
Explanation: In the second day, the first and the third flower have become blooming.

Example 2:

Input: 
flowers: [1,2,3]
k: 1
Output: -1

Note:

  1. The given array will be in the range [1, 20000].

思路

本题目描述中的数组索引是从1开始的,这和程序猿们通常让索引从0开始的习惯有所出入。为了统一,我们在描述中对于索引还是从1开始,只是在实现中稍加改变。

思路是:我们额外定义一个数组days,用来表示每朵花的开花时间,例如days[i] = y表示在位置i上的花的开花时间是第y天。那么问题就转化为:给定days数组之后,找出一个子区间[left, left + 1, ...left + k - 1, right),满足对于任意的i = left + 1,...left + k - 1,满足days[left] < days[i] && days[right] < days[i]。如果找到了,就返回true,否则就返回false。

代码

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        vector<int> days(flowers.size());
        for(int i = 0; i < flowers.size(); ++i) {
            days[flowers[i] - 1] = i + 1;
        }
        int left = 0, right = k + 1, res = INT_MAX;
        for(int i = 0; right < days.size(); ++i) {
            if(days[i] < days[left] || days[i] <= days[right]) {   
                if(i == right) {
                    res = min(res, max(days[left], days[right]));    // we get a valid subarray
                }
                left = i, right = k + 1 + i;
            }
        }
        return (res == INT_MAX)? -1 : res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值