当前位置:网站首页>The 25th day of the special assault version of the sword offer
The 25th day of the special assault version of the sword offer
2022-08-10 03:20:00 【_hys】
排序+贪心
- Sort the interval by the left endpoint in ascending order,Then there is a property:The left endpoint of the next interval<=当前右端点<=当前左端点.
- It is easy to think that it is impossible to merge if the current right endpoint is smaller than the left endpoint of the next interval,If it is greater than or equal to, then take the maximum of the current right endpoint and the next right endpoint.
class Solution {
public:
bool cmp(vector<int> &a, vector<int> &b) {
if(a[0] != b[0]) return a[0] < b[0];
return a[1] < b[1];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
int st = intervals[0][0], ed = intervals[0][1];
vector<vector<int>> res;
for(int i = 1; i < intervals.size(); i++) {
const auto seg = intervals[i];
if(ed < seg[0]) {
res.emplace_back(vector<int>{
st,ed});
st = seg[0];
ed = seg[1];
} else {
ed = max(ed,seg[1]);
}
}
if(res.empty() || ed != res.back()[1]) res.emplace_back(vector<int>{
st,ed});
return res;
}
};
计数排序
发现 a r r 1 arr1 arr1 range of data [ 0 , 1000 ] [0,1000] [0,1000] It can be directly counted and sorted, O ( N ) O(N) O(N) 的时间复杂度.
注意:After you finish inserting the front part,whileconditions will appear-1,需要加上>0条件.
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
int cnts[1010] = {
0};
vector<int> res;
for(auto num: arr1) cnts[num]++;
for(auto num: arr2)
while(cnts[num]--) res.emplace_back(num);
for(int i = 0; i <= 1000; i++)
while(cnts[i]-- > 0)
res.emplace_back(i);
return res;
}
};
边栏推荐
猜你喜欢
随机推荐
剑指offer专项突击版第25天
2022年8月8日-2022年8月15日,ue4视频教程+插件源码()
.Net interview experience summary
2022.8.8考试区域链接(district)题解
华为HCIE云计算之FC添加ipsan数据存储
小菜鸟河北联通上岗培训随笔
微透镜阵列的高级模拟
STM32F103驱动HCSR04超声波测距显示
gbase 8a数据库如何查看数据或数据文件是否正常?
状态压缩小经验
数据在内存中的存储
QT中,QTableWidget 使用示例详细说明
官宣出自己的博客啦
3dmax如何制作模型走路动画
Go语言JSON文件的读写操作
官宣出自己的博客了
SQL注入的order by ,limit与宽字节注入
OpenCV图像处理学习二,图像掩膜处理
2022.8.9考试立方和--1100题解
Screen 拆分屏幕