개발자식

[Codility Lesson4] Counting Elements_MissingInteger 본문

Algorithm/Codility

[Codility Lesson4] Counting Elements_MissingInteger

밍츠 2022. 6. 30. 03:36

문제 : MissingInteger

 

Test results - Codility

This is a demo task. Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A =

app.codility.com

 

나의 코드

- Detected time complexity: O(N) or O(N * log(N))

- 마이너스로만 이루어진 경우 먼저 확인 -> return 1

- 리스트를 순회하면서 마이너스 값은 넘어가게 설정

- 값이 1인 경우는 특별히 확인하는 변수 설정 (1이 없다면 어떤 수가 와도 1 return) 

- 나머지 경우는 이전 값과 1 차이가 안난다면 이전 값 +1 return 

- 위에 해당하지 않는 경우 (ex 1,2,3,4,,,)는 리스트 마지막 값 +1

def solution(A):
    temp=list(set(A))
    temp.sort()
    if max(A) <=0:
        return 1
    check=False
    for i in range(len(temp)):
        if temp[i]<=0:
            continue
        if temp[i]==1:
            check=True
            continue
        if not check:
            return 1
        if temp[i]-temp[i-1] !=1:
            return temp[i-1]+1
    return temp[-1]+1

 

정답 코드

- Detected time complexity: O(N) or O(N * log(N))

def solution(A):
    A.sort()
    min = 1
    for i in A:
        if i == min:
            min += 1
    return min

 

깔끔하군,,,,

Comments