几道经典算法题

1根据前序中序重建二叉树

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null||pre.length==0||in==null||in.length==0){
            return null;
        }
        if(pre.length!=in.length){
            return null;
        }

        TreeNode node=new TreeNode(0);
        for(int i=0;i<in.length;i++){
            if(in[i]==pre[0]){

               node.val=in[i];

       node.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));          
       node.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
       }
        }
       return node; 

    }
}

2数值的整数次方

import java.util.*;
public class Solution {
    public double Power(double base, int exponent) {
        if(base==0&&exponent<0) return 0.0;

        int abs=Math.abs(exponent);
        if(exponent>0){
            return pow(base,abs);
        }else if(exponent<0){
            return 1/pow(base,abs);
        }else {
            return 1.0;
        }

  }

    public double pow(double base,int abs){
        if(abs==1)return base;
        double result=pow(base,abs>>1);//abs>>1代表abs/2
        result*=result;
        if((abs&1)==0){//abs&1结果为0的话abs为偶数,为1为奇数(用0判断,对2求余也用0判断)
        return result;
        }else{
          return result*base;
        }

    }
}

3判断五个数是不是顺子,大小王用0表示
(判断0的个数是不是大于总的间隙的个数,出现对子返回false)

import java.util.*;
public class Solution {
    public boolean isContinuous(int [] numbers) {
        if(numbers==null||numbers.length==0){
            return false;
        }
        Arrays.sort(numbers);
        //统计数组中的0的个数
        int zCount=0;
        for(int a:numbers){
            if(a==0) zCount++;
        }
        int gCount=0;
        for(int i=zCount;i1;i++){
            if(numbers[i]==numbers[i+1]) return false;
            gCount+=(numbers[i+1]-numbers[i]-1);
        }
        return (zCount>=gCount)?true:false;





    }
}

你可能感兴趣的:(算法+数据结构)