๋ฌธ์
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
ํด๊ฒฐ๋ฐฉ์
- ์ ๋ ฅ๋ ๋ฐฐ์ด A์ ์ต๋๊ฐ์ด 0๋ณด๋ค ์๋ค๋ฉด ๋ชจ๋ ์์๋ก ๊ตฌ์ฑ๋ ๋ฐฐ์ด์ด๊ธฐ ๋๋ฌธ์ 1์ ๋ฐํ
- 1๋ถํฐ N(A.count)๊น์ง ์ ์๋ค๋ก ๊ตฌ์ฑ๋ Set(์งํฉ) ์์ฑ
- 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 |