当前位置:   article > 正文

代码随想录算法训练营第三十二天|LeetCode 738,968,总结

代码随想录算法训练营第三十二天|LeetCode 738,968,总结

目录

LeetCode 738.单调递增的数字

LeetCode 968.监控二叉树

总结


LeetCode 738.单调递增的数字

文章讲解:代码随想录

视频讲解:贪心算法,思路不难想,但代码不好写!LeetCode:738.单调自增的数字_哔哩哔哩_bilibili

力扣题目:力扣

 

 

代码如下(Java):

  1. class Solution {
  2. public int monotoneIncreasingDigits(int n) {
  3. String[] strings = (n + "").split("");
  4. int start = strings.length;
  5. for(int i = strings.length - 1; i > 0; i--){
  6. if(Integer.parseInt(strings[i]) < Integer.parseInt(strings[i - 1])){
  7. strings[i - 1] = (Integer.parseInt(strings[i - 1]) - 1) + "";
  8. start = i;
  9. }
  10. }
  11. for(int i = start; i < strings.length; i++){
  12. strings[i] = "9";
  13. }
  14. return Integer.parseInt(String.join("", strings));
  15. }
  16. }

 

LeetCode 968.监控二叉树

文章讲解:代码随想录

视频讲解:贪心算法,二叉树与贪心的结合,有点难...... LeetCode:968.监督二叉树_哔哩哔哩_bilibili

力扣题目:力扣

 

 代码如下(Java):

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. int res = 0;
  18. public int minCameraCover(TreeNode root) {
  19. if(minCame(root) == 0) res++;
  20. return res;
  21. }
  22. public int minCame(TreeNode root){
  23. if(root == null) return 2;
  24. int left = minCame(root.left);
  25. int right = minCame(root.right);
  26. if(left == 2 && right == 2){
  27. return 0;
  28. }else if(left == 0 || right == 0){
  29. res++;
  30. return 1;
  31. }else{
  32. return 2;
  33. }
  34. }
  35. }

 

总结

文章讲解:代码随想录

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/836363
推荐阅读
相关标签
  

闽ICP备14008679号