๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โŒจ๏ธ Language/swift

[Swift] Codility Lesson 4 - MissingInteger

by hyebin (Helia) 2022. 7. 24.
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

๋ฌธ์ œ ๋งํฌ
 

MissingInteger coding task - Learn to Code - Codility

Find the smallest positive integer that does not occur in a given sequence.

app.codility.com

GitHub
 

GitHub - yoohyebin/swift

Contribute to yoohyebin/swift development by creating an account on GitHub.

github.com

 

๋ฌธ์ œ ๋ถ„์„

  • N๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐฐ์—ด A๊ฐ€ ์ฃผ์–ด์ง€๋ฉด, A์— ์—†๋Š” ๊ฐ€์žฅ ์ž‘์€ ์–‘์˜ ์ •์ˆ˜(0๋ณด๋‹ค ํผ)๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
ex)
A = [1, 3, 6, 4, 1, 2]  5
A = [1, 2, 3]              4
A = [-1, -3]               1

 

ํ•ด๊ฒฐ๋ฐฉ์•ˆ

  1. ์ž…๋ ฅ๋œ ๋ฐฐ์—ด A์˜ ์ตœ๋Œ“๊ฐ’์ด 0๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๋ชจ๋‘ ์Œ์ˆ˜๋กœ ๊ตฌ์„ฑ๋œ ๋ฐฐ์—ด์ด๊ธฐ ๋•Œ๋ฌธ์— 1์„ ๋ฐ˜ํ™˜
  2. 1๋ถ€ํ„ฐ N(A.count)๊นŒ์ง€ ์ •์ˆ˜๋“ค๋กœ ๊ตฌ์„ฑ๋œ Set(์ง‘ํ•ฉ) ์ƒ์„ฑ
  3. Set๊ณผ A์˜ ์ฐจ์ง‘ํ•ฉ์ด ์กด์žฌํ•˜๋ฉด ์ฐจ์ง‘ํ•ฉ์ค‘ ์ž‘์€ ๊ฐ’์„ ๋ฐ˜ํ™˜, ์—†๋‹ค๋ฉด N+1 ๋ฐ˜ํ™˜

Solution

public func solution(_ A : inout [Int]) -> Int {
    if A.max()! <= 0 {
        return 1
    }
    let setB = Set(1...A.count)

    if let re = setB.subtracting(A).min(){
        return re
    }else{
        return A.count+1
    }
}

  • ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N) or O(N * log(N))
๋ฐ˜์‘ํ˜•

'โŒจ๏ธ Language > swift' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Swift] Codility Lesson 5 - CountDiv  (0) 2022.07.26
[Swift] Codility Lesson 5 - PassingCars  (0) 2022.07.26
[Swift] Codility Lesson 4 - MaxCounters  (0) 2022.07.23
[Swift] Codility Lesson 4 - PermCheck  (0) 2022.07.23
[Swift] Codility Lesson 4 - FrogRiverOne  (0) 2022.07.23