一个简单的算法优化的示例

本文通过Python代码展示了三种不同的算法,分别用于解决某个问题。方法一的时间复杂度为O(n^3),耗时132秒;方法二和方法三的时间复杂度同为O(n^2),但方法三的运行时间略快于方法二,分别为9.10669e8和8.39676e8纳秒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

直接用python代码的形式来看

# 问题
# a + b + c = 1000
# a*a + b*b = c*c
# 求 a b c

在以上问题求解的基础上,在此实现了三种算法,实现代码和输出结果以及算法复杂度T如下所示:

方法一

import time

# 方法一
start_time = time.time()

for a in range(0,1001):
    for b in range(0, 1001):
        for c in range(0, 1001):
            if a+b+c ==1000 and a**2 +b**2 == c**2:
                print('a, b, c: %d %d %d ' %(a,b,c))

end_time = time.time()

print('method_1 cost time is : %d s'%(end_time-start_time))
print('finished method 1 ')

输出结果

a, b, c: 0 500 500 
a, b, c: 200 375 425 
a, b, c: 375 200 425 
a, b, c: 500 0 500 
method_1 cost time is : 132s
finished method 1

可以看出消耗时间上有132秒,method 1 时间复杂度为 T(n) = O(n^3)

方法二

# 方法二
start_time = time.time_ns()
for a in range (0,1001):
    for b in range (0,1001):
        if a**2 + b**2 ==(1000-a-b)**2:
            print('a, b, c: %d %d %d ' % (a, b, 1000-a-b))

end_time = time.time_ns()

print('method_2 cost time is : %d ns'%(end_time-start_time))
print('finished method 2')

输出结果为如下所示

a, b, c: 0 500 500 
a, b, c: 200 375 425 
a, b, c: 375 200 425 
a, b, c: 500 0 500 
method_2 cost time is : 910669000 ns

注意:1s = 1 000 000 000 ns,  method_2 cost time is : 910 669 000ns,意味着不到1s

同时 method_2 时间复杂度 T(n) = O(n^2)

方法三

# 方法三
start_time = time.time_ns()
c = [print(a,b,(1000-a-b )) for a in range(0,1001) for b in range(0,1001) if a**2+b**2 == (1000-a-b)**2 ]
end_time = time.time_ns()
print('method_3 cost time is : %d ns'%(end_time-start_time))
print('finished method 3')

输出结果如下所示

0 500 500
200 375 425
375 200 425
500 0 500
method_3 cost time is : 820679000 ns
finished method 3

可以看出 method_3 cost time is : 839 676 000ns,方法三比方法二略快一点 

方法三的时间复杂度 T (n)= O(n^2),方法二和方法三 的时间复杂度是一样的

 

目前为止就想到这三种算法,mark

参考自https://www.bilibili.com/video/av46256220?from=search&seid=3284016986363356908

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值