几道经典算法题
来源:互联网 发布:网络文明与安全演说稿 编辑:程序博客网 时间:2024/04/28 01:24
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;i<numbers.length-1;i++){ if(numbers[i]==numbers[i+1]) return false; gCount+=(numbers[i+1]-numbers[i]-1); } return (zCount>=gCount)?true:false; }}
0 0
- 几道经典算法题
- 几道经典C 语言笔试题
- 几道经典SQL笔试题
- 几道经典DP
- 【算法】两道经典地图算法题
- 几道经典的数据结构算法代码实现(1)
- 几道经典的数据结构算法代码实现(2)
- 100道经典算法题(26-50)
- 100道经典算法题(51-75)
- 100道经典算法题(76-100)
- Python的100道经典算法题
- 几道经典SQL学习
- 几道经典笔试题目
- 几道经典面试题
- SPFA几道经典题目
- 几道经典的几何作图趣题
- 几道经典的嵌入式C语言笔试题
- 几道经典的嵌入式C语言笔试题
- 浅谈cookie和session的关系
- 不确定性学习(1)
- Go语言程序设计:集合类型
- 中山大学(大三感想)
- BP神经网络的matlab实现
- 几道经典算法题
- 多线程之间及多进程间的通信
- android 在绘制椭圆,圆时遇到函数计算
- CCF习题 201312-4有趣的数 (DP)
- 数据结构=多种结构比较(1)——栈
- Android MVP+Retrofit+RxJava实践小结
- View的事件体系(1)-View基础知识
- 菲利普-泰特洛克的超预测速成课程(目录)
- JavaScript中的垃圾回收