Codility lesson time complexity and my answer memo (Python)

Task: Maxcounters It is an individual impression.

①Speed N*M

def solution(N, A):
    anslist = [0] * N
    maxvalue = 0
    for i in A:
        try:
            anslist[i-1] += 1
        except:
            maxvalue = max(anslist)
            anslist = [maxvalue] * N
    return anslist
Impressions and learning

I thought that if I did max in every try, it would be N * 2, so I tried to max only when necessary. But, of course, it depends on the frequency of appearance of N + 1, so it will be N * M. Convinced.

②Speed: N+M

def solution(N, A):
    anslist = [0] * N
    maxchecker = 0
    for i in A:
        try:
            anslist[i-1] += 1
            if anslist[i-1] > maxchecker:
                maxchecker = anslist[i-1]
        except:
            anslist = [maxchecker] * N
    return anslist

Impressions and learning: I don't know why N ** + M ** ??? .. .. Suspect. And I haven't reached speed N or Log (N).

Recommended Posts

Codility lesson time complexity and my answer memo (Python)
[My memo] python
[Python] Conversion memo between time data and numerical data
My python environment memo
[My memo] python -v / python -V
Python Tips (my memo)
Python execution time measurement memo
Python and ruby slice memo
Python memo ① Folder and file operations
Statistical basics and Python, graphing, etc. (memo)
A memo with Python2.7 and Python3 on CentOS
Python data structure and operation (Python learning memo ③)
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
The answer of "1/2" is different between python2 and 3
Reading and writing fits files with Python (memo)
progate Python learning memo (updated from time to time)
To represent date, time, time, and seconds in Python