重建二叉树
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
TreeNode treeNode = new TreeNode(pre[0]);
for (int i = 0; i < in.length; i++){
if (pre[0] == in[i]) {
treeNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
treeNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
}
}
return treeNode;
}
}
两个栈实现队列
分析:二分查找变种,没有具体的值用来比较。那么用中间值和高低位进行比较,看处于递增还是递减序列,进行操作缩小范围。
处于递增:low上移
处于递减:high下移(如果是high-1,则可能会错过最小值,因为找的就是最小值)
其余情况:low++缩小范围
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.size()<=0){
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
jk旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array.length==0)
return 0;
int left=0;
int right=array.length-1;
int mid=0;
while(left<right){
mid=left+(right-left)/2;
if(array[left]<array[right])
return array[left];
if(array[left]<array[mid]){
left=mid+1;
}
else if(array[mid]<array[right]){
right=mid;
}
else{
left++;
}
}
return array[left];
}
}
斐波那契数列
分析
观察上一版发现,sum 只在每次计算第 n 项的时候用一下,其实还可以利用 sum 存储第 n-1 项,例如当计算完 f(5) 时 sum 存储的是 f(5) 的值,当需要计算 f(6) 时,f(6) = f(5) + f(4),sum 存储的 f(5),f(4) 存储在 one 中,由 f(5)-f(3) 得到
public class Solution {
public int Fibonacci(int n) {
if(n==0){
return 0;
}else if (n==1){
return 1;
}
int sum=0;
int one=0;
int two=1;
for(int i=2;i<=n;i++){
sum=two+one;
one=two;
two=sum;
}
return sum;
}
}
跳台阶
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
public class Solution {
public int JumpFloor(int target) {
if(target<=2){
return target;
}
int one=1;
int two=2;
int sum=0;
for(int i=3;i<=target;i++){
sum=one+two;
one=two;
two=sum;
}
return sum;
}
}
变态跳台阶
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
public class Solution {
public int JumpFloorII(int target) {
int one=1;
int sum=0;
if(target==1)
return target;
for(int i=2;i<=target;i++){
sum=2*one;
one=sum;
}
return sum;
}
}