简体   繁体   中英

Programming Challenge Code taking too much time

I wrote the following code for 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)

But the code is producing a Time Limit Exceeded Error. Earlier I had tried using a in for every item in student but it produced a TLE and I believe that's because the in statement is O(n) . So, I wrote this code whose steps required are roughly equal to the sum of the lengths of both the lists. But this is also producing a TLE. So, what changes should I make in my code. Is there some particular part which has a high time expense?

Thanks.

You are using sorting + merging. This takes O(NlogN + MlogM + N + M) time complexity.

But you can put professor data in a set , check every student year value (from an unsorted list) and get O(M + N) complexity (on average).

Note that this approach eliminates the long operation of student list sorting.

Addition: python has built-in sets. For languages that have no such provision, the professor's list is already sorted, so you can just use binary search for every year. The complexity would be O(NlogM) .

As the problem basically is to find the intersection of two sets of integers the following code solves the problem in O(M + N) when assuming that a dictionary access is possible in O(1)

prof = set([int(input()) for x in range(int(input()))])
student = set([int(input()) for x in range(int(input()))])

equals_dates = len(prof.intersection(student))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM