当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
2022-04-23 14:09:00 【白马非马·】
题目:x的n次方,结果输出
package demo4_8;
public class leijia {
static int temp;
public static void main(String[] args) {
//一道题目思考递归的时间复杂度
//问题:x的n次方
int x=2;
int n=8;
System.out.println("方法一:"+method1(x,n));
System.out.println("方法二:"+method2(x,n));
System.out.println("方法三:"+method3(x,n));
System.out.println("方法四:"+method4(x,n));
}
//方法一:直接求解(时间复杂度为O(n)
public static int method1(int x,int n){
int result=1;
for(int i=0;i<n;i++){
result*=x;
}
return result;
}
//方法二:递归的方法:时间复杂度还是O(n)
public static int method2(int x,int n){
if(n==0) return 1;
return method2(x,n-1)*x;
}
//方法三:递归的方法:时间复杂度还是O(n)
//通过满二叉树进行计算,时间复杂度还是O(n)
public static int method3(int x,int n){
if(n==0) return 1;
if(n%2==1) return method3(x,n/2)*method3(x,n/2)*x;
return method3(x,n/2)*method3(x,n/2);
}
//方法四:递归的方法:时间复杂度还是O(n)
public static int method4(int x,int n){
if(n==0) return 1;
temp=method4(x,n/2); //记录中间变量
System.out.println("次数");
if(n%2==1) return temp*temp*x;
return temp*temp;
}
}
版权声明
本文为[白马非马·]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42974034/article/details/124055567
边栏推荐
- 预览CSV文件
- 容灾有疑问?点这里
- RecyclerView高级使用(一)-侧滑删除的简单实现
- MYSQL 主从同步避坑版教程
- Wechat applet input hidden and inoperable settings
- 政务云迁移实践 北明数科使用HyperMotion云迁移产品为某政府单位实施上云迁移项目,15天内完成近百套主机迁移
- Research on recyclerview details - Discussion and repair of recyclerview click dislocation
- 微信小程序客服接入,实现发送和接收消息
- How QT designer adds resource files
- Multiple inheritance virtual base exercises
猜你喜欢
随机推荐
MySQL数据库讲解(十)
MYSQL一种分表实现方案及InnoDB、MyISAM、MRG_MYISAM等各种引擎应用场景介绍
Storage path of mod subscribed by starbound Creative Workshop at Star boundary
01-NIO基础之ByteBuffer和FileChannel
VMWare安装64位XP中文教程
Promtail + Loki + Grafana 日志监控系统搭建
Essential difference between restful WebService and gSOAP webservice
报表FCRA考试题集及答案(错了11题)
Returns the subscript after array sorting
Idea控制台乱码解决
帆软分割求解:一段字符串,只取其中某个字符(所需要的字段)
Research on recyclerview details - Discussion and repair of recyclerview click dislocation
Wechat applet positioning and ranging through low-power Bluetooth device (2)
mysql查询库大小
yml引用其他变量
Date的after时间判断
ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory
使用开源调研工具Prophet是一种什么体验?
HyperMotion云迁移完成阿里云专有云产品生态集成认证
线程间控制之Semaphore使用介绍