【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树

LeetCode题目链接

https://leetcode.cn/problems/merge-intervals/

https://leetcode.cn/problems/monotone-increasing-digits/

https://leetcode.cn/problems/binary-tree-cameras/

题解

56.合并区间

自己写出来了,好棒。需要注意神奇的语句end = max(end, intervals[i][1]);

738.单调递增的数字

这题注意int和string类型转换的方法,转成数字9的做法。

968.监控二叉树

难题,下周目写。

代码

cpp 复制代码
//56.合并区间
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
private:
    static bool cmp(const vector<int> a, const vector<int> b) {
        if (a[0] == b[0]) return a[1] < b[1];
        return a[0] < b[0];
    }
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>>result;
        if (intervals.size() == 0) return result;
        sort(intervals.begin(), intervals.end(), cmp);
        int end = intervals[0][1], start = intervals[0][0];
        for (int i = 1;i < intervals.size();i++) {
            if (end < intervals[i][0]) {
                result.push_back({ start, end });
				start = intervals[i][0];
				end = intervals[i][1];
            }
            else {
                end = max(end, intervals[i][1]);
            }
        }
        result.push_back({ start, end });
        return result;
    }
};

int main() {
    vector<vector<int>> nums1 = { {1,3} ,{2,6},{8,10},{15,18} }, nums2 = { {1,4} ,{4,5} }, nums3 = { {4,7} ,{1,4} }, nums4 = { {1,4} ,{2,3} };
	Solution s;
    vector<vector<int>> result = s.merge(nums4);
    for (int i = 0;i < result.size();i++) {
        for (int j = 0;j < result[i].size();j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    return 0;
}
cpp 复制代码
//738.单调递增的数字
相关推荐
小O的算法实验室19 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
郭涤生20 小时前
STL vector 扩容机制与自定义内存分配器设计分析
c++·算法
༾冬瓜大侠༿20 小时前
vector
c语言·开发语言·数据结构·c++·算法
Ricky111zzz21 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
汀、人工智能21 小时前
[特殊字符] 第58课:两个正序数组的中位数
数据结构·算法·数据库架构··数据流·两个正序数组的中位数
liu****21 小时前
第16届省赛蓝桥杯大赛C/C++大学B组(京津冀)
开发语言·数据结构·c++·算法·蓝桥杯
汀、人工智能21 小时前
[特殊字符] 第79课:分割等和子集
数据结构·算法·数据库架构·位运算·哈希表·分割等和子集
汀、人工智能21 小时前
[特殊字符] 第74课:完全平方数
数据结构·算法·数据库架构·图论·bfs·完全平方数
CoderCodingNo21 小时前
【GESP】C++四、五级练习题 luogu-P1177 【模板】排序
数据结构·c++·算法
Proxy_ZZ021 小时前
从零实现LDPC比特翻转译码器:C语言实战与底层逻辑解析
c语言·算法