系列文章目录
【拒绝算法PUA】0x00-位运算
【拒绝算法PUA】0x01- 区间比较技巧
【拒绝算法PUA】0x02- 区间合并技巧
【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中
C++刷题技巧总结:
[温习C/C++]0x04 刷题基础编码技巧
LeetCode 2274. 不含特殊楼层的最大连续楼层数
链接
题目
Alice 管理着一家公司,并租用大楼的部分楼层作为办公空间。Alice 决定将一些楼层作为 特殊楼层 ,仅用于放松。
给你两个整数 bottom 和 top ,表示 Alice 租用了从 bottom 到 top(含 bottom 和 top 在内)的所有楼层。另给你一个整数数组 special ,其中 special[i] 表示 Alice 指定用于放松的特殊楼层。
返回不含特殊楼层的 最大 连续楼层数。
示例 1:
输入:bottom = 2, top = 9, special = [4,6]
输出:3
解释:下面列出的是不含特殊楼层的连续楼层范围:
- (2, 3) ,楼层数为 2 。
- (5, 5) ,楼层数为 1 。
- (7, 9) ,楼层数为 3 。
因此,返回最大连续楼层数 3 。
示例 2:
输入:bottom = 6, top = 8, special = [7,6,8]
输出:0
解释:每层楼都被规划为特殊楼层,所以返回 0 。
提示
1 <= special.length <= 105
1 <= bottom <= special[i] <= top <= 109
special 中的所有值 互不相同
解题方法1
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxConsecutive(int bottom, int top, vector<int>& special) {
int ret = 0;
vector<vector<int>> book;
vector<int> buildings;
for (int i = 0; i < top + 1; i++) {
buildings.push_back(i);
}
std::sort(special.begin(), special.end(), std::less<int>());
int left = bottom;
for (auto& right : special) {
vector<int> vec {};
while (left < right) {
vec.push_back(buildings[left]);
left++;
}
book.push_back(vec);
int nn = vec.size();
ret = max(ret, nn);
left += 1;
}
if (left < top) {
vector<int> tmpVec;
tmpVec.insert(tmpVec.end(), buildings.begin() + left, buildings.end());
book.push_back(tmpVec);
int nn = tmpVec.size();
ret = max(ret, nn);
}
return ret;
}
};
int main(int argc, char **argv) {
Solution obj;
int bottom = 2;
int top = 9;
vector<int>special = {6,4};
int ret = obj.maxConsecutive(bottom, top, special);
cout << ret << endl;
return 0;
}
输出:
3
解题方法2(代码优化版本)
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxConsecutive(int bottom, int top, vector<int>& special) {
int ret = 0;
std::sort(special.begin(), special.end(), std::less<int>());
vector<pair<int, int>> book;
int left = bottom;
for (int i = 0; i < special.size(); i++) {
int right = special[i];
book.push_back({left, right - 1});
ret = max(ret, right - 1 - left + 1);
left = right + 1;
}
if (left < top) {
book.push_back({left, top});
ret = max(ret, top - left + 1);
}
return ret;
}
};