카테고리 없음

Lesson 4 Counting Elements MissInteger 나만의풀이

친구들안녕 2021. 6. 2. 10:07

문제

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 = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];each element of array A is an integer within the range [−1,000,000..1,000,000].

대충 해석하자면 A는 N개의 정수가 있는데 0보다 큰 가장 작은수를 반환한다.

[1, 3, 6, 4, 1, 2]가 있으면 return 5

 

 

첫 번째 시도

별 다른 생각 없이 시도했던 첫번째 시도

어마어마하게 많이 틀렸다... 

def solution(A):
    A = list(set(A))

    if A[-1]>0:
        if len(A)==1:
            return A[0]+1
        now_val = -1000000000
        for i in A:
            if i>0:
                if now_val == -1000000000:
                    now_val = i
                else:
                    if i-now_val>1:
                        return now_val+1
                    now_val = i
        return A[-1]+1

    return 1

 

 

 

두 번째 시도 이후 많은 시간이 지났다..

결국 못 풀었다 ㅋㅋㅋ

왜일까요? 문제를 찾다가 결국 못 찾아서 다른 사람들의 풀이를 봤다.

이렇게 간단하게 풀다니... 그리고 내껄 봤다. 내 식대로 만들어서 풀어봤는데 또 틀렸다...

알고보니 sort를 안해서 틀린 문제 ㅋㅋ

list(set(A)) 하고 프린트 했더니 정렬되어 보이길래 정렬 안해도 되는줄 알았다.

그러나 보이기만 그렇지 실상 정렬이 되어있지 않다는거... 잊지 말아야지

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