LeetCode 683. K Empty Slots
原题链接
困难
作者:
JasonSun
,
2020-02-12 02:22:42
,
所有人可见
,
阅读 811
Algorithm (Sorted Set)
- Create a sorted set structure to store the positions of turned on bulbs. We denote this structure as S.
- We insert into S the positions of bulb in increasing order or days. After each insertion at day d, we query the higher and lower positions of the inserted element and calculate the corresponding distance ℓlower and ℓupper; if any of the two is equal to K+2, we return d. Otherwise, we return −1 as instructed.
Code (Cpp17)
class Solution {
public:
int kEmptySlots(vector<int>& bulbs, int K) {
const auto n = size(bulbs);
auto higher = [&](const std::set<int> &x, int val) -> optional<int> {
auto it = x.upper_bound(val);
if (it == std::end(x))
return std::nullopt;
else
return *it;
};
auto lower = [&](const std::set<int> &x, int val) -> optional<int> {
auto it = x.lower_bound(val);
if (it == std::begin(x))
return std::nullopt;
else
return *(--it);
};
const auto solution = [&] {
struct state_t { std::set<int> prev; };
for (auto [i, state] = pair{0, state_t{}}; i < n; ++i) {
state.prev.insert(bulbs[i]);
const auto h = higher(state.prev, bulbs[i]);
const auto l = lower(state.prev, bulbs[i]);
if (h and std::abs(*h - bulbs[i]) + 1 == K + 2)
return i + 1;
else if (l and std::abs(*l - bulbs[i]) + 1 == K + 2)
return i + 1;
}
return -1;
}();
return solution;
}
};