Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] MissingInteger #137

Closed
hwangJi-dev opened this issue Mar 22, 2023 · 0 comments
Closed

[Algorithm] MissingInteger #137

hwangJi-dev opened this issue Mar 22, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Mar 22, 2023

๐Ÿ’ฌย ๋ฌธ์ œ

https://app.codility.com/programmers/lessons/4-counting_elements/missing_integer/


๐Ÿ’ฌย Idea

  • N ์ •์ˆ˜์˜ ๋ฐฐ์—ด A๊ฐ€ ์ฃผ์–ด์ง€๋ฉด A์—์„œ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š” ๊ฐ€์žฅ ์ž‘์€ ์–‘์˜ ์ •์ˆ˜(0๋ณด๋‹ค ํผ)๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•˜๋ฏ€๋กœ
  • ์šฐ์„  A๋ฅผ ์ •๋ ฌํ•œ ๋’ค A์—์„œ 1๋ณด๋‹ค ์ž‘์€ ์ˆ˜๋ฅผ ๋ชจ๋‘ ํ•„ํ„ฐ๋งํ•ด์ฃผ์—ˆ๋‹ค.
  • ์ดํ›„ ๊ฒฐ๊ณผ๊ฐ€ ๋นˆ ๋ฐฐ์—ด์ด๋ผ๋ฉด 1์„ ๋ฆฌํ„ดํ•˜์—ฌ ๋นจ๋ฆฌ ๊ฒฐ๊ณผ๊ฐ’์„ ๋„์ถœํ•ด์ฃผ์—ˆ๊ณ , ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด for๋ฌธ์„ ๋Œ๋ฉฐ preInteger(์ด์ „ ์ •์ˆ˜ ๊ฐ’)์™€ ์ •๋ ฌ๋œ ์›์†Œ์˜ ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉฐ ๊ทธ ์ฐจ์ด๊ฐ€ 1 ์ดˆ๊ณผ์ธ ๊ฒฝ์šฐ์— ๊ฐ€์žฅ ์ž‘์€ ์–‘์˜ ์ •์ˆ˜๋ฅผ ๋„์ถœํ•˜๊ธฐ ์œ„ํ•ด preInteger + 1 ์„ ๋ฆฌํ„ดํ•ด์ฃผ์—ˆ๋‹ค.
  • ๋งŒ์•ฝ for๋ฌธ์„ ๋‹ค ๋Œ๊ณ ๋„ ๊ฐ€์žฅ ์ž‘์€ ์ •์ˆ˜๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ๋‹ค๋ฉด 1 ์ด์ƒ์˜ ๋ชจ๋“  ์›์†Œ๊ฐ€ ์ฑ„์›Œ์ ธ์žˆ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ Set(A)์˜ ๊ฐœ์ˆ˜ + 1์„ ํ•ด์„œ ๊ทธ ๋‹ค์Œ์œผ๋กœ ์ž‘์€ ์ˆ˜๋ฅผ ๋ฆฌํ„ดํ•ด์ฃผ์—ˆ๋‹ค.

๐Ÿ’ฌย ํ’€์ด

import Foundation

public func solution(A : inout [Int]) -> Int {
    A = A.sorted()
    A = A.filter({ $0 >= 1 })
    
    if A.isEmpty { return 1 }
    
    var preInteger = 0
    
    for i in A {
        if i - preInteger > 1 {
            return preInteger + 1
        } else {
            preInteger = i
        }
    }
    
    return Set(A).count + 1
}

์†Œ์š”์‹œ๊ฐ„ : 16๋ถ„

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

ํ‰๊ฐ€ํ‘œ : https://app.codility.com/demo/results/trainingK7RBSR-4DF/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant