683. K Empty Slots
我的思路:
首先,题目用的变量有点奇怪,注意这点:
flowers[i] = xmeans that the unique flower that blooms at day
iwill be at position
x
其次,题目中有这么一句话:
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 ,我们插入开放一朵新的花在 B1,B2 之间,那么这时候,对于连续不开放花的影响只有 B1,Bn+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;
}
};