ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [codility] Counting Elements - MissingInteger
    Algorithm 2021. 9. 24. 00:39

    문제

    This is a demo task.

    Write a function:

    public func solution(_ A : inout [Int]) -> 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].Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

     

    문제 해설

    가장 작은 양의 정수를 리턴

    A 배열이 주어지면 순열이 아닌 형태 [1,2,3,4,6] 5를 리턴

    [1,2,3] 4를 리턴

    [-1, -3] 1을 리턴

     

    구현 해설

    set을 이용해서 순차적으로 배열을 순회하면서 값이 없으면 가장 작은 정수로 판단

     

    import Foundation
    import Glibc
    
    // you can write to stdout for debugging purposes, e.g.
    // print("this is a debug message")
    
    public func solution(_ A : inout [Int]) -> Int {
        // write your code in Swift 4.2.1 (Linux)
        let sets = Set<Int>(A)
        for index in 1...Int.max {
            if !sets.contains(index) {
                return index
            }
        }
        return -1
    }

    댓글

Designed by Tistory.