classSolution{int result;//定义全局变量记录经过某节点的路径最大长度publicintdiameterOfBinaryTree(TreeNode root){//递归
result =0;postorder(root);return result;}//递归函数,分别计算二叉树中每个节点左右子树的最大深度,经过该节点的最大路径长度为左右子树最大深度之和privateintpostorder(TreeNode root){//终止条件if(root ==null)return0;//后序遍历int left =postorder(root.left);int right =postorder(root.right);
result =Math.max(result, left + right);returnMath.max(left, right)+1;}}
classSolution{publicintfindUnsortedSubarray(int[] nums){//双指针int leng = nums.length;if(leng ==1)return0;int left =0;int right =0;int max =Integer.MIN_VALUE;int min =Integer.MAX_VALUE;for(int i =0; i < leng; i++){if(max > nums[i]){
right = i;}else{
max = nums[i];}if(min < nums[leng - i -1]){
left = leng - i -1;}else{
min = nums[leng - i -1];}}//若left和right在同一位置,说明数组有序,返回0return left == right ?0: right - left +1;}}
classSolution{publicintcountSubstrings(String s){//双指针中心扩展//遍历字符串,以一个元素后两个元素为中心向两边扩散int result =0;for(int i =0; i < s.length(); i++){
result +=count(s, i, i);
result +=count(s, i, i +1);}return result;}//计算当前中心的回文子串个数privateintcount(String s,int i,int j){//左右指针分别向中心两边扩散,每扩散一次若字符相同则回文子串数加1int result =0;while(i >=0&& j < s.length()&& s.charAt(i)== s.charAt(j)){
result++;
i--;
j++;}//直到字符不同,返回当前中心的回文子串个数return result;}}
classSolution{publicint[]dailyTemperatures(int[] temperatures){//栈头值最小,使用单调栈存储下标Deque<Integer> stack =newLinkedList<>();int[] result =newint[temperatures.length];//遍历数组,如果当前温度大于栈顶下标对应温度,则出栈for(int i =0; i < temperatures.length; i++){if(!stack.isEmpty()){while(!stack.isEmpty()&& temperatures[i]> temperatures[stack.peek()]){int index = stack.pop();//并计算栈顶下标的下一次高温(当前下标-栈顶下标)
result[index]= i - index;}//直到当前温度小于栈顶下标对应温度,当前下标入栈。
stack.push(i);}else{
stack.push(i);}}return result;}}