我正在尝试解决HackerRank上的this问题,该问题要求您对整数列表进行排序,并找出将数字移动多少次才能以正确的升序排列(在问题)。
我的代码通过了12个测试用例中的8个,但是当输入太大而出现超时错误时失败。这似乎是HackerRank上的一个常见指标,表明代码对于手头的问题而言太慢了。那么有没有一种方法可以优化此代码,使其在较大的数据集上运行得更快?
def minimum_bribes(queue):
"""Returns the minimum number of bribes people in a queue accepted."""
# Variable to keep track of bribes
bribes = 0
# Check if queue is too chaotic
for i in queue:
index = queue.index(i)
if i - index > 3:
return "Too chaotic"
# Use a bubble sort to find number of bribes
for i in range(len(queue) - 1):
for j in range(len(queue) - 1 - i):
if queue[j] > queue[j + 1]:
queue[j], queue[j + 1] = queue[j + 1], queue[j]
bribes += 1
return bribes
# Number of test cases
t = int(input())
results = []
for _ in range(t):
# Number of people
n = int(input())
# Final State of queue
q = list(map(int, input().rstrip().split()))
# Add bribe counts to results array
results.append(minimum_bribes(q))
# Print results
for result in results:
print(result)
答案 0 :(得分:2)
我建议使用while循环来测试条件,如果先前的迭代中没有交换,则无需运行新的交换迭代。
def minimumBribes(queue):
for i in queue:
index = queue.index(i)
if (i - index) > 3:
print("Too chaotic")
return
n = len(queue)
swap =0
swapped = True
j =0
while swapped:
j+=1
swapped = False
for i in range(n-j):
if queue[i] > queue[i+1]:
queue[i], queue[i+1] = queue[i+1], queue[i]
swap +=1
swapped = True
print(swap)
return swap