Turbo sort - Time Limit Exceeded

て烟熏妆下的殇ゞ 提交于 2020-01-24 12:53:45

问题


Am trying to solve a Codechef problem (Turbo Sort). The problem is

Given the list of numbers, you are to sort them in non decreasing order.

Input

t – the number of numbers in list, then t lines follow [t <= 10^6].

Each line contains one integer: N [0 <= N <= 10^6]

Output

Output given numbers in non decreasing order.

Example

Input:

5 5 3 6 7 1

Output:

1 3 5 6 7

My Solution is :

l = []
t = input()
MAX = 10**6
while t <= MAX and t != 0:
    n = input()
    l.append(n)
    t = t - 1
st = sorted(l)
for x in st:
    print x

The challenge is this program should run in 5 sec. When i submit the file, codechef says it is exceeding the time and needs optimization.

Can some one help, how to optimize it ?


回答1:


My accepted solutions:

import sys
from itertools import imap
T = int(raw_input())
lines = sys.stdin.readlines()
lis = imap(str, sorted(imap(int, lines)))
print "\n".join(lis)

A readable version(accepted solution) :

import sys
T = raw_input()           
lines = sys.stdin.readlines() #fetch all lines from the STDIN
lines.sort(key=int)           #sort the list in-place(faster than sorted) 
print "\n".join(lines)        #use `str.join` instead of a for-loop



回答2:


Things like readlines should be supported. I've just made an attempt and got this as an accepted solution:

import sys
print '\n'.join(map(str, sorted(map(int, sys.stdin.read().split()[1:]))))

Not pretty but functional. Took me a bit before I figured out you had to skip the first number, debugging is a bit annoying with this system ;)



来源:https://stackoverflow.com/questions/17430539/turbo-sort-time-limit-exceeded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!