[英]Complexity for two approaches of finding next biggest palindrome of a number
I have come up with a problem online about the next biggest palindrome of a number and i have solved the problem by two different approaches in python. 我在网上提出了有关下一个最大回文数的问题,并且我已经通过python中的两种不同方法解决了该问题。 The first one is, 第一个是
t = long(raw_input())
for i in range(t):
a = (raw_input())
a = str(int(a) + 1)
palin = ""
oddOrEven = len(a) % 2
if oddOrEven:
size = len(a) / 2
center = a[size]
else:
size = 0
center = ''
firsthalf = a[0 : len(a)/2]
secondhalf = firsthalf[::-1]
palin = firsthalf + center + secondhalf
if (int(palin) < int(a)):
if(size == 0):
firsthalf = str(int(firsthalf) + 1)
secondhalf = firsthalf[::-1]
palin = firsthalf + secondhalf
elif(size > 0):
lastvalue = int(center) + 1
if (lastvalue == 10):
firsthalf = str(int(firsthalf) + 1)
secondhalf = firsthalf[::-1]
palin = firsthalf + "0" + secondhalf
else:
palin = firsthalf + str(lastvalue) + secondhalf
print palin
and the another one is, 另一个是
def inc(left):
leftlist=list(left)
last = len(left)-1
while leftlist[last]=='9':
leftlist[last]='0'
last-=1
leftlist[last] = str(int(leftlist[last])+1)
return "".join(leftlist)
def palin(number):
size=len(number)
odd=size%2
if odd:
center=number[size/2]
else:
center=''
print center
left=number[:size/2]
right = left[::-1]
pdrome = left + center + right
if pdrome > number:
print pdrome
else:
if center:
if center<'9':
center = str(int(center)+1)
print left + center + right
return
else:
center = '0'
if left == len(left)*'9':
print '1' + (len(number)-1)*'0' + '1'
else:
left = inc(left)
print left + center + left[::-1]
if __name__=='__main__':
t = long (raw_input())
while t:
palin(raw_input())
t-=1
As a computer science perspective, what is the complexity of both of this algorithms? 从计算机科学的角度来看,这两种算法的复杂性是什么? which one is more efficient to use? 哪个更有效?
I see you are making a sublist within your for loop, and the largest sublist is of size n-1. 我看到您正在for循环中创建一个子列表,并且最大的子列表的大小为n-1。 And then a loop that goes to n. 然后循环到n。
So worst case for both is O(n^2), where n is the length of t. 因此,两者的最坏情况是O(n ^ 2),其中n是t的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.