59.合并区间
class Solution {
public:
struct cmp{
bool operator()(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
};
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.size() == 1)
return intervals;
sort(intervals.begin(), intervals.end(), cmp());
int begin = intervals[0][0];
int end = intervals[0][1];
vector<vector<int>> res;
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i][0] <= end) {
if (end <= intervals[i][1]) {
end = intervals[i][1];
}
} else {
res.push_back(vector<int>{begin, end});
begin = intervals[i][0];
end = intervals[i][1];
}
}
res.push_back(vector<int>{begin, end});
return res;
}
};
738.单调递增的数字
暴力解法超时
贪心思路:
- 例如 98
- strNum[i - 1] > strNum[i] 时, strNum[i - 1]减一, strNum[i]赋值9, 结果则是 89
- flag 则是避免 100 的情况出现
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string str = to_string(n);
int flag = str.size();
for (int i = str.size() - 1; i > 0; i--) {
if (!(str[i - 1] <= str[i])) {
str[i - 1] --;
flag = i;
}
}
for (int i = flag; i < str.size(); i++) {
str[i] = '9';
}
return stoi(str);
}
};
968.监控二叉树
后续补充