알고리즘

[Codility][Kotlin] PermMissingElem

jordancancode 2024. 10. 3. 23:27

문제

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

fun solution(A: IntArray): Int

that, given an array A, returns the value of the missing element.

For example, given array A such that:

A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5

the function should return 4, as it is the missing element.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].

 

풀이

private fun solution1(A: IntArray): Int {
    var result = 0
    val B = BooleanArray(A.size+2){false}
    for (i in A.indices) {
        B[A[i]] = true
    }
    for (j in B.indices) {
        if( !B[j] ) result = j
    }
    return result
}
//등차수열의 합이 (n)(n+1)/2임을 활용하여 A라는 Array의 각 수들의 합과 비교하여 구함
private fun solution2(A: IntArray): Int {
    val n = (A.size+1).toLong()
    val sequence = n*(1+n)/2L
    val sum = A.sum().toLong()

    return (sequence-sum).toInt()
}

 solution1은 나의 풀이, solution2는 인터넷에서 기똥찬 풀이가 있어 가져왔다!

반응형