LeetCode 0683

683. K Empty Slots

原题链接

我的思路:

首先,题目用的变量有点奇怪,注意这点:

flowers[i] = xmeans that the unique flower that blooms at dayiwill be at positionx

其次,题目中有这么一句话:

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.

这是说,对于给定的k,你要找到这么一天,使得存在两朵已经开的花,并且这两朵花之间有k朵花,并且这k朵花都是没有开放的。

那么一种思路就是,遍历每一天,使得一朵花开放之后,是否存在连续k朵不开放的花。假设有n朵已经开放的花 B1,B2,,Bn ,我们插入开放一朵新的花在 B1B2 之间,那么这时候,对于连续不开放花的影响只有 B1Bn+1 以及 Bn+1,B2 有影响

我从网上找了一份代码,利用的是set的有序性:

class Solution {
public:
    int kEmptySlots(vector<int>& flowers, int k) {
        set<int> bloom;
        for (int i = 0; i < flowers.size(); i++) {
            int p = flowers[i];
            bloom.insert(p);
            auto it = bloom.find(p);
            if (it != bloom.begin()) {
                if (p-*(--it) == k+1) return i+1;
                it++;
            }
            if (it != bloom.end() && *(++it)-p == k+1) return i+1; 
        }
        return -1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值