当前位置:网站首页>时间复杂度计算举例
时间复杂度计算举例
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
边栏推荐
- 金融行业云迁移实践 平安金融云整合HyperMotion云迁移解决方案,为金融行业客户提供迁移服务
- 帆软调用动态传参的方法,在标题中设置参数
- 关于训练过程中损失函数出现断崖式增长的问题
- Recyclerview advanced use (I) - simple implementation of sideslip deletion
- Detailed tutorial on the use of smoke sensor (mq-2) (based on raspberry pie 3B +)
- 星界边境Starbound创意工坊订阅的mod的存放路径
- 返回数组排序后下标
- 数据库DbVisualizer Pro报文件错误,导致数据连接失败
- 困扰多年的系统调研问题有自动化采集工具了,还是开源免费的
- 服务器日志分析工具(识别,提取,合并,统计异常信息)
猜你喜欢
ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory
01-NIO基础之ByteBuffer和FileChannel
postman批量生产body信息(实现批量修改数据)
Installation and use of postman pit
关于密匙传递的安全性和数字签名
微信小程序客服接入,实现发送和接收消息
sql中出现一个变态问题
VMWare安装64位XP中文教程
Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
Wechat applet positioning and ranging through low-power Bluetooth device (2)
随机推荐
回顾2021:如何帮助客户扫清上云最后一公里的障碍?
Homebrew是什么?以及使用
报表FCRA考试题集及答案(错了11题)
使用开源调研工具Prophet是一种什么体验?
rsync+inotify远程同步
jsp学习1
Logging module
困扰多年的系统调研问题有自动化采集工具了,还是开源免费的
How to do a project easily
Idea控制台乱码解决
MYSQL 主从同步避坑版教程
Wechat applet positioning and ranging through low-power Bluetooth device (2)
服务器日志分析工具(识别,提取,合并,统计异常信息)
Some experience of using dialogfragment and anti stepping pit experience (getactivity and getdialog are empty, cancelable is invalid, etc.)
Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
Detailed tutorial on the use of setinterval timing function of wechat applet
DP energy Necklace
mysql 5.1升级到5.66
返回数组排序后下标
帆软中使用if else 进行判断-使用标题条件进行判断