968
This commit is contained in:
whai 2024-03-06 16:48:43 +08:00
parent 50cafa2cb5
commit 2dabc83adb
3 changed files with 155 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package cn.whaifree.leetCode.Greedy;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/3/6 15:24
* @注释
*/
public class LeetCode738 {
@Test
public void test() {
System.out.println(new Solution().monotoneIncreasingDigits(65832));
}
class Solution {
/**
* 98一旦出现strNum[i - 1] > strNum[i]的情况非单调递增首先想让strNum[i - 1]减一strNum[i]赋值9因为要最大的数用9一定满足非递减这样这个整数就是89
* @param N
* @return
*/
public int monotoneIncreasingDigits(int N) {
String[] strings = (N + "").split("");
int start = strings.length;
// 出现递减的两个 前一个-1找到最先递减的的indexindex后面全部为9
for (int i = strings.length - 1; i > 0; i--) {
if (Integer.parseInt(strings[i]) < Integer.parseInt(strings[i - 1])) {
strings[i - 1] = (Integer.parseInt(strings[i - 1]) - 1) + "";
start = i;
}
}
for (int i = start; i < strings.length; i++) {
strings[i] = "9";
}
return Integer.parseInt(String.join("",strings));
}
}
class Solution1 {
public int monotoneIncreasingDigits(int n) {
String s = String.valueOf(n);
char[] chars = s.toCharArray();
int start = s.length();
for (int i = s.length() - 2; i >= 0; i--) {
if (chars[i] > chars[i + 1]) {
chars[i]--;
start = i+1;
}
}
for (int i = start; i < s.length(); i++) {
chars[i] = '9';
}
return Integer.parseInt(String.valueOf(chars));
}
}
}

View File

@ -0,0 +1,66 @@
package cn.whaifree.leetCode.Greedy;
import cn.whaifree.leetCode.model.TreeNode;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/3/6 16:34
* @注释
*/
public class LeetCode968 {
@Test
public void test() {
System.out.println(new Solution().minCameraCover(TreeNode.constructTreeByArray(1, 2, null, 2, 4, 6)));
}
/**
* 我们分别有三个数字来表示
*
* 0该节点无覆盖
* 1本节点有摄像头
* 2本节点有覆盖
*/
class Solution {
int res = 0;
public int minCameraCover(TreeNode root) {
// 根节点
if (travel(root) == 0) {
res++;
}
return res;
}
public int travel(TreeNode root) {
if (root == null) {
return 2;
}
int left = travel(root.left);
int right = travel(root.right);
// 左右节点都有覆盖
if (left == 2 && right == 2) return 0;
//左或右无覆盖本节点要增加摄像头
if (left == 0 || right == 0) {
res++;
return 1;
}
// 左或右有摄像头本节点被覆盖
if (left == 1 || right == 1) {
return 2;
}
return -1;
}
}
}

View File

@ -1,5 +1,7 @@
package cn.whaifree.leetCode;
import java.util.ArrayList;
/**
*
*
@ -114,3 +116,25 @@ class ListNode {
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class RefCountGC{
// 这个成员属性的唯一作用就是占用一点内存
private byte[] bigSize = new byte[5*1024*1024];
// 引用
Object reference = null;
byte[]buffer = new byte[1*1024*1024];//1MB
public static void main(String[] args) {
ArrayList<RefCountGC> list = new ArrayList<>();
int count = 0;
try {
while (true) {
list.add(new RefCountGC());
count++;
}
}catch(Throwable e){
System.out.println("count" + count);
e.printStackTrace();
}
}
}