Python 采访街';s插入排序程序
我试图编程Interiewstreet的插入排序挑战 在Python中,下面是我的代码 该程序对于输入元素的限制(我不确定)运行良好,但对于较大的输入返回错误的输出。谁能告诉我我做错了什么Python 采访街';s插入排序程序,python,insertion-sort,Python,Insertion Sort,我试图编程Interiewstreet的插入排序挑战 在Python中,下面是我的代码 该程序对于输入元素的限制(我不确定)运行良好,但对于较大的输入返回错误的输出。谁能告诉我我做错了什么 # This program tries to identify number of times swapping is done to sort the input array """ =>Get input values and print them =>Get number of tes
# This program tries to identify number of times swapping is done to sort the input array
"""
=>Get input values and print them
=>Get number of test cases and get inputs for those test cases
=>Complete Insertion sort routine
=>Add a variable to count the swapping's
"""
def sort_swap_times(nums):
""" This function takes a list of elements and then returns the number of times
swapping was necessary to complete the sorting
"""
times_swapped = 0L
# perform the insertion sort routine
for j in range(1, len(nums)):
key = nums[j]
i = j - 1
while i >= 0 and nums[i] > key:
# perform swap and update the tracker
nums[i + 1] = nums[i]
times_swapped += 1
i = i - 1
# place the key value in the position identified
nums[i + 1] = key
return times_swapped
# get the upper limit.
limit = int(raw_input())
swap_count = []
# get the length and elements.
for i in range(limit):
length = int(raw_input())
elements_str = raw_input() # returns a list of strings
# convert the given elements from str to int
elements_int = map(int, elements_str.split())
# pass integer elements list to perform the sorting
# get the number of times swapping was needed and append the return value to swap_count list
swap_count.append(sort_swap_times(elements_int))
# print the swap counts for each input array
for x in swap_count:
print x
您的算法是正确的,但这是解决问题的一种幼稚方法,在大型测试用例(即len(nums)>10000)上会给您一个时间限制超出信号。让我们分析一下算法的运行时复杂性
for j in range(1, len(nums)):
key = nums[j]
i = j - 1
while i >= 0 and nums[i] > key:
# perform swap and update the tracker
nums[i + 1] = nums[i]
times_swapped += 1
i = i - 1
# place the key value in the position identified
nums[i + 1] = key
上述代码段中所需的步骤数与1+2+..+成正比len(nums)-1或len(nums)*(len(nums)-1)/2步,即O(len(nums)^2)
提示:
使用所有值都在[1,10^6]范围内的事实。这里真正要做的是找到列表中的倒数,即找到所有i如果哪个整数的值较大,则会给出错误的输出?@izomorphius,该站点包含一个要在程序上运行的测试用例列表。错误输出是什么意思?TLE或WA?我收到了TLE错误消息,但只通过了几个测试用例