LeetCode 0683

来源:互联网 发布:斯诺登现状2017 知乎 编辑:程序博客网 时间:2024/06/01 10:50

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;    }};
原创粉丝点击