简体   繁体   中英

The run time is too long

When I test it with code, there is no error, but it fails with a timeout.

Problem

The failure rate is defined as follows. Number of players / number of players as far as stage is concerned The total number N of stages, the game can be currently stopped by the user. .

Limitations

The number N of stages is a natural number of 1 or more and 500 or less. The length of the stage is 1 or more and 200,000 or less. Contains natural water above step 1 and below N + 1. Each natural number is currently being challenged by the user. N + 1 is the final stage. There is still a failure rate. The success rate of the stage is zero.

My code

def solution(N, stages):
    fail = []
    for i in range(1,N+1):
        no_clear = stages.count(i)
        he_stage = sum([stages.count(x) for x in range(i,N+2)])
        if no_clear==0: 
            fail.append((i,0))
        else: 
            fail.append((i,no_clear/he_stage))
    fail=sorted(fail,key=lambda x: (-x[1],x[0]))
    print(fail)
    return [fail[i][0] for i in range(N)]

I suppose stages is a list . Calling count repeatedly on a list has a very high complexity, specially if you're doing that in a loop.

You could use a cache or maybe simpler: replace stages.count(x) by a collections.Counter object call

before:

def solution(N, stages):
    fail = []
    for i in range(1,N+1):
        no_clear = stages.count(i)
        he_stage = sum([stages.count(x) for x in range(i,N+2)])

after:

import collections
def solution(N, stages):
   fail = []
   stages_counter = collections.Counter(stages)
   for i in range(1,N+1):
       no_clear = stages_counter[i]
       he_stage = sum(stages_counter[x] for x in range(i,N+2))

This will reduce your complexity a great deal. Elements are counted once and for all. Just access the dictionary in O(1) time once it's done.

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