编辑
2024-05-11
算法题
00
请注意,本文编写于 364 天前,最后修改于 364 天前,其中某些信息可能已经过时。

image.png

java
public class Solution { public int garbageCollection(String[] garbage, int[] travel) { int[] lastPos = new int[]{-1,-1,-1}; // 记录每种垃圾最后出现的位置 int[] time = new int[4]; // 记录每种垃圾收拾所需的时间 int count = 0; // 遍历垃圾数组,记录每种垃圾最后出现的位置 for (int i = 0; i < garbage.length; i++) { for (int j = 0; j < garbage[i].length(); j++) { char c = garbage[i].charAt(j); if (c == 'M') { lastPos[0] = i; count++; //time[0] += travel[i]; } else if (c == 'P') { lastPos[1] = i; count++; //time[1] += travel[i]; } else if (c == 'G') { lastPos[2] = i; count++; //time[2] += travel[i]; } } } //System.out.println(lastPos[2]); -1,2,3 // 计算收拾每种垃圾所需的时间 for (int i = 0; i < 3; i++) { if (lastPos[i] > 0) { for(int j = 0; j < lastPos[i];j++) { time[i]=time[i]+ travel[j]; } System.out.println(time[2]); //time[i] += lastPos[i] * travel[lastPos[i] - 1]; } } // 返回收拾所有垃圾所需的时间 return time[0] + time[1] + time[2] + count; } }

image.png

java
public class Solution { private int minDiff = Integer.MAX_VALUE; private Integer prevVal = null; public int getMinimumDifference(TreeNode root) { inorder(root); return minDiff; } private void inorder(TreeNode node) { if (node == null) { return; } inorder(node.left); // 左子树 if (prevVal != null) { minDiff = Math.min(minDiff, node.val - prevVal); } prevVal = node.val; // 更新前一个节点的值 inorder(node.right); // 右子树 } }

image.png

java
public class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean isValidBST(TreeNode node, long lower, long upper) { if (node == null) { return true; } // 当前节点的值必须在lower和upper之间 if (node.val <= lower || node.val >= upper) { return false; } // 递归验证左子树和右子树 return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper); } }

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!