1.二维数组中的查找
public class Solution{
public boolean Find(int target,int [][] array){
int row=0;
int col=array[0].length-1;
while(row<=array.length-1&&col>=0){
if(target==array[row][col]){
return true;
}else if(target>array[row][col]){
row++;
}else{
col--;
}
}
return false;
}
}
思路:1.二维数组的性质
a.每一行按照从左到右递增的顺序排序
b.每一列都按照从上到下递增的顺序排序
用某行最小或某列最大与target比较,每次可剔除一整行或一整列
对于左下角的值m,m是该行最小的数,是该列最大的数(m=array[row][col])
每次将m和目标值target比较:
1.当target==array[row][col],找到该值,返回true;
2.当target<array[row][col],col--;(由于m已经是该列最小的元素,想要更小只有从行考虑,取值上移一位)
3.当target>array[row][col],row++;(由于m已经是该行最大的元素,想要更大只有从列考虑,取值右移一位)
2.重建二叉树
import java.util.Arrays;
public class Solution{
public TreeNode reConstructBinaryTree(int [] pre,int [] in){
if(pre.length==0||in.length==0){
return null;
}
TreeNode root=new TreeNode(pre[0]);
for(int i=0;i<in.length;i++){
if(in[i]==pre[0]){
root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
}
思路:1.如果前序和中序遍历的结果的长度为0,返回null;
2.创建一个树,树的根节点为前序遍历的结果索引为0的数。
3.循环:通过前序遍历找到树的根节点,通过中序遍历中找到根节点,分为左子树和右子树。in[i]==pre[0];
4.在通过前序遍历的结果和中序遍历的结果,继续判断左/右子树的根节点和叶子节点。
3.菲波那切数列
public class Solution{
public int Fibonacci(int n){
if(n==0) return 0;
if(n==1) return 1;
int sum=1;
int one=0;
for(int i=2;i<=n;i++){
sum=sum+one;
one=sum-one;
}
return sum;
}
}
思路:F(n)=F(n-1)+F(n-2);