代码随想录算法训练营第三一天| 56. 合并区间 738.单调递增的数字 968.监控二叉树
今日任务
56. 合并区间
738.单调递增的数字
968.监控二叉树
56. 合并区间
题目链接: . - 力扣(LeetCode)
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a,b)->a[0] - b[0]);
if (intervals.length == 1) {
return intervals;
}
int left = intervals[0][0];
int right = intervals[0][1];
List<int[]> res = new ArrayList<>();
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] > right) {
res.add(new int[]{left, right});
left = intervals[i][0];
right = intervals[i][1];
} else {
right = Math.max(right, intervals[i][1]);
}
}
res.add(new int[]{left, right});
int[][] result = new int[res.size()][2];
for (int i = 0; i < res.size(); i++) {
result[i] = res.get(i);
}
return result;
}
}
738.单调递增的数字
题目链接: . - 力扣(LeetCode)
class Solution {
public int monotoneIncreasingDigits(int n) {
String s = String.valueOf(n);
char[] charArray = s.toCharArray();
int start = charArray.length;
for (int i = s.length() - 2; i >= 0; i--) {
if (charArray[i] > charArray[i + 1]) {
start = i + 1;
charArray[i]--;
}
}
for (int i = start; i < charArray.length; i++) {
charArray[i] = '9';
}
return Integer.parseInt(String.valueOf(charArray));
}
}
968.监控二叉树
题目链接: . - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = 0;
public int minCameraCover(TreeNode root) {
if (minCamera(root) == 0) {res++;}
return res;
}
public int minCamera(TreeNode root) {
/*
* 0 表示该节点无覆盖
* 1 表示该节点有摄像头
* 2 表示该节点无摄像头,但有覆盖
* */
if (root == null) {return 2;}
int left = minCamera(root.left);
int right = minCamera(root.right);
if (left == 2 && right == 2) { return 0;}
else if (left == 0 || right == 0) {res++; return 1;}
else {return 2;}
}
}