문제
This is a demo task.
Write a function:
fun solution(A: IntArray): 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].
풀이
fun solution(A: IntArray): Int {
var As = mutableSetOf<Int>()
val max = A.maxOrNull()?:1
if(max <= 0)
return 1
for(i in 1 .. max+1){
As.add(i)
}
A.forEach{
if(A.contains(it)){
As.remove(it)
}
}
return As.minOrNull()?:1
}
굉장히 만족스럽지 않은 결과가 나왔다. 시간 복잡도는 O(N^2)...
풀이2
fun solution(A : IntArray) : Int {
val present = BooleanArray(A.size+2)
A.forEach {
if (it>0 && it <= A.size+1)
present[it] = true
}
for (i in 1..A.size+1){
if (!present[i]) {
return i
}
}
return A.size+1
}
BooleanArray 짱짱~! 시간복잡도 O(NlogN)으로 성공했다~
반응형
'알고리즘' 카테고리의 다른 글
[C++] SWEA [모의 SW 역량테스트] 미생물 격리 (1) | 2024.11.13 |
---|---|
[C++] SWEA D3. [S/W 문제해결 기본] 1일차 - View (0) | 2024.11.12 |
[Codility][Kotlin]PermCheck (1) | 2024.10.04 |
[Codility][Kotlin] FrogRiverOne (0) | 2024.10.04 |
[Codility][Kotlin] TapeEquilibrium (0) | 2024.10.03 |