36.两个链表的第一个公共节点
两个链表的节点同步移动,如果走到链表尾,则继续走另外一个链表,这样当两个节点相遇时,他们都走了len(表1)+len(表2)-公共段长度
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while(p1!=p2){
p1=p1==null?pHead2:p1.next;
p2=p2==null?pHead1:p2.next;
}
return p1;
}
}
37.数字在排序数列中出现的次数
从左记录第一个等于该值的下标,从右记录第一个等于该值的下标,二者相减,注意加一。
public class Solution {
public int GetNumberOfK(int [] array , int k) {
if(array.length==0){
return 0;
}
if(k>array[array.length-1]||k<array[0]){
return 0;
}
int i =0;
int j =array.length-1;
while(array[i]<k&&i<array.length){
i++;
}
while(array[j]>k&&j>0){
j--;
}
return j-i+1;
}
}
38.二叉树的深度
递归求法
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left>right?left+1:right+1;
}
}
39.平衡二叉树
平衡二叉树的条件之一就是左右子树深度不能超过1,依此进行判断。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getDep(root)!=-1;
}
public int getDep(TreeNode root){
if(root==null){
return 0;
}
int left = getDep(root.left);
if(left==-1){
return -1;
}
int right = getDep(root.right);
if(right==-1){
return -1;
}
return Math.abs(left-right)>1?-1:Math.max(left,right)+1;
}
}
40.数组中只出现一次的数字
借用了栈,根据相邻的值是否相同,判断是否出栈,最后剩余的就是所求的两个只出现一次的数。
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
import java.util.*;
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
Arrays.sort(array);
Stack<Integer> st = new Stack();
for(int x :array){
if(st.isEmpty()){
st.push(x);
}else if(st.peek()==x){
st.pop();
}else{
st.push(x);
}
}
num1[0]=st.pop();
num2[0]=st.pop();
}
}