代码随想录算法训练营第三十一天-56合并区间、738单调递增的数字、968监控二叉树
初步题解
56 合并区间
题目链接:(https://leetcode.cn/problems/merge-intervals)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public static int[][] merge(int[][] intervals) { ArrayList<int[]> list = new ArrayList<>(); Arrays.sort(intervals, (o1, o2) -> { if (o1[0] == o2[0]) { return o1[1] - o2[1]; } return o1[0] - o2[0]; }); if (intervals.length <= 1) { return intervals; } int start = intervals[0][0]; int end = intervals[0][1]; for (int i = 1; i < intervals.length; i++) { if (intervals[i][0] > intervals[i - 1][1]) { list.add(new int[]{start, end}); start = intervals[i][0]; end = intervals[i][1]; } else { end = Math.max(end, intervals[i][1]); intervals[i][1] = end; } } list.add(new int[]{start, end}); return list.toArray(new int[list.size()][]); }
|
738 单调递增的数字
题目链接:(https://leetcode.cn/problems/monotone-increasing-digits)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public static int monotoneIncreasingDigits(int n) { String num = n + ""; if (num.length() <= 1) { return n; } char[] chars = num.toCharArray(); for (int i = chars.length - 1; i >= 1; i--) { if (chars[i - 1] > chars[i]) { chars[i - 1]--; for (int j = i; j < chars.length; j++) { chars[j] = '9'; } } } return Integer.parseInt(String.valueOf(chars)); }
public static int monotoneIncreasingDigits(int n) { String num = n + ""; if (num.length() <= 1) { return n; } int start = -1; char[] chars = num.toCharArray(); for (int i = chars.length - 1; i >= 1; i--) { if (chars[i - 1] > chars[i]) { chars[i - 1]--; start = i;
} } if (start != -1) { for (int j = start; j < chars.length; j++) { chars[j] = '9'; } } return Integer.parseInt(String.valueOf(chars)); }
|
968 监控二叉树
题目链接:(https://leetcode.cn/problems/binary-tree-cameras)
看解析
56 合并区间
解析:(https://programmercarl.com/0056.合并区间.html)
738 单调递增的数字
解析:(https://programmercarl.com/0738.单调递增的数字.html)
968 监控二叉树
解析:(https://programmercarl.com/0968.监控二叉树.html)
思路:本题要从叶子节点分析,贪心贪叶子节点的上一个节点为摄像头(这种情况下摄像头最少)。然后,根据节点状态,一共分了 3 种:0 无覆盖;1 有摄像头;2 有覆盖。按照下图的思路做题,就可以解出,还是比较难想的。
内链:[[968监控二叉树图示.excalidraw]]
外链:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| int res = 0; public int minCameraCover(TreeNode root) { if (minCameraCoverTravel(root) == 0) { res++; } return res; } private int minCameraCoverTravel(TreeNode root) { if (root == null) { return 2; } int left = minCameraCoverTravel(root.left); int right = minCameraCoverTravel(root.right); if (left == 2 && right == 2) { return 0; } else if (left == 0 || right == 0) { res++; return 1; } else { return 2; } }
|