我寫了下面的代碼爲this problem.編程挑戰賽典花費過多時間
prof = sorted([int(input()) for x in range(int(input()))])
student = sorted([int(input()) for x in range(int(input()))])
prof_dates = len(prof)
stud_dates = len(student)
amount = 0
prof_index = 0
stud_index = 0
while stud_index < stud_dates and prof_index < prof_dates:
if student[stud_index] == prof[prof_index]:
amount += 1
stud_index += 1
elif student[stud_index] > prof[prof_index]:
prof_index += 1
elif student[stud_index] < prof[prof_index]:
stud_index += 1
print(amount)
但代碼生成一個時間超出限制錯誤。之前我曾嘗試在學生中爲每個項目使用in
,但它產生了TLE,我相信這是因爲in
聲明是O(n)
。所以,我寫了這段代碼,其步驟要求大致等於兩個列表長度的總和。但是這也產生了一個TLE。所以,我應該在我的代碼中做出什麼樣的改變。有一些特定的部分有很高的時間開銷嗎?
謝謝。
爲什麼downvote時,下面的代碼解決了
O(M + N)
問題? –由於代碼正在工作,這可能更適合[codereview.se]。 – usr2564301