简体   繁体   中英

How to deal with excessively large inputs in python?

I am a beginner and I was practicing a question on hackerrank. I wrote this code as part of a problem which timed out for large inputs:

    K = int(input())
    roomnos = input().split()
    setroomnos = set(roomnos)
    for r in setroomnos:
        if roomnos.count(r) == 1:
            print(r)
            break

The next one was accepted by the judge for all test cases

    K = int(input())
    roomnos = [int(i) for i in input().split()]
    setroomnos = set(roomnos)
    c = (K * sum(setroomnos) - sum(roomnos)) // (K - 1)
    print(c)

can you please explain why the first one timed out for large inputs and the second one worked fine PS: The fundamental operation is to find a no which appears only once in a list as opposed to other nos which appear K times

Your first solution uses O(n) for with an O(n) count inside it - leading to O(n^2) complexity. Your second example doesn't nest operations in that way, and so is O(n) complexity.

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