Cute Blue Flying Butterfly
본문 바로가기
알고리즘

[Codility][Kotlin] MissingInteger

by jordancancode 2024. 10. 7.

문제

This is a demo task.

Write a function:

fun solution(A: IntArray): Int

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].

 

풀이

fun solution(A: IntArray): Int {
    var As = mutableSetOf<Int>()
    val max = A.maxOrNull()?:1
    if(max <= 0)
        return 1
    for(i in 1 .. max+1){
        As.add(i)
    }
    A.forEach{
        if(A.contains(it)){
            As.remove(it)
        }
    }
    return As.minOrNull()?:1
}

굉장히 만족스럽지 않은 결과가 나왔다. 시간 복잡도는 O(N^2)...

 

풀이2

fun solution(A : IntArray) : Int {
    val present = BooleanArray(A.size+2)
    A.forEach { 
        if (it>0 && it <= A.size+1)
            present[it] = true
    }
    for (i in 1..A.size+1){
        if (!present[i]) {
            return i
        }
    }
    return A.size+1
}

BooleanArray 짱짱~! 시간복잡도 O(NlogN)으로 성공했다~

반응형