# 牛客剑指Offer刷题汇总-2020/2/05-JAVA

1.二叉树的深度

AC源码：


public class Solution
{
public int TreeDepth(TreeNode root)
{
if(root == null)
{
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left,right)+1;
}
}


2.平衡二叉树

AC源码：

public class Solution
{
public boolean IsBalanced_Solution(TreeNode root)
{
return getDepth(root) != -1;
}
private int getDepth(TreeNode root)
{
if(root == null)
return 0;
int left = getDepth(root.left);
if(left == -1)
return -1;
int right = getDepth(root.right);
if(right == -1)
return -1;
return Math.abs(left-right)>1? -1 :1+Math.max(left,right);
}
}


3.和为S的两个数字

1).x+y=sum就是结果
2).x+y>sum y–
3).x+y<sum x++
AC源码：

import java.util.ArrayList;
public class Solution
{
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum)
{
ArrayList<Integer> result =new ArrayList<>();
int x=0;
int y=array.length-1;
while(x<y)
{
if(array[x]+array[y])==sum
{
break;
}
else if(array[x]+array[y]>sum)
{
y--;
}
else
{
x++;
}
}
return result;
}
}


4.数组中只出现一次的数字

AC源码：

public class Solution
{
public void FindNumsAppearOnce(int[] array,int[]num1,int[]num2)
{
int length=array.length;
if(length==2)
{
num1[0]=array[0];
num2[0]=array[1];
return;
}
int bitResult=0;
for(int i=0;i<length;i++)
bitResult ^= array[i];
int index = findFirst1(bitResult);
for(int i=0;i<length;i++)
{
if(isBit1(array[i],index))
num1[0]^=array[i];
else
num2[0]^=array[i];
}
}
private int findFirst1(int bitResult)
{
int index=0;
while(((bitResult&1)==0)&&index<32)
{
bitResult >>=1;
index++;
}
return index;
}
private boolean isBit1(int target,int index)
{
return ((target>>index)&1)==1;
}
}


5.和为S的连续正数序列

AC源码：

import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
int plow = 1,phigh = 2;
while(phigh > plow){
int cur = (phigh + plow) * (phigh - plow + 1) / 2;
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i=plow;i<=phigh;i++){
}
plow++;
}else if(cur < sum){
phigh++;
}else{
plow++;
}
}
return result;
}
}


04-01 181
06-02 2976
02-25 1303
09-30 704
11-25 871
11-03 230
12-13 704
12-28 139
12-29 19
12-27 126
10-18 2万+