티스토리 뷰

Coding Test/Swift

Codility - MaxCounters

범무룩 2020. 8. 4. 11:57

app.codility.com/programmers/lessons/4-counting_elements/

 

4. Counting Elements lesson - Learn to Code - Codility

Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.

app.codility.com

문제

  • 마지막 카운터의 배열을 반환하라

조건

  • counter(X) -> arr[k] <= N -> K번째 1증가.

  • max Counter -> arr[k] == N+1 -> 모든 카운터 Max값

풀이

  • Arr[N] 개 만든다.

  • A[K] <= N 이면 K-1 index 에 있는 Arr[k-1]++

  • 이 때 Max값을 가지고 있는다.

  • A[K] == N+1 Max값으로 변환

  • A.count 만큼 실행

import Foundation
import Glibc

public func solution(_ N : Int, _ A : inout [Int]) -> [Int] {
    // - Arr[N] 개 만든다.
    var resultArr = Array<Int>(repeating: 0, count: N)
    var maxValue = 0
    // - A[K] <= N 이면 K-1 index 에 있는 Arr[k-1]++
    A.forEach { item in
        let index = item-1
        if index < N {
            resultArr[index] += 1
            if maxValue < resultArr[index] {
                maxValue = resultArr[index]
            }
        } else {
            resultArr = resultArr.map { _ in maxValue }
        }
    }

    return resultArr
}

실행시간 O(N*M)


실행시간이 커 제한된 시간 내에 들어오지 못하였다.

따라서 시간을 줄일 방법을 모색하였다.

public func solution(_ N : Int, _ A : inout [Int]) -> [Int] {
    // - Arr[N] 개 만든다.
    var resultArr = Array<Int>(repeating: 0, count: N)
    var maxValue = 0
    var baseValue = 0
    // - A[K] <= N 이면 K-1 index 에 있는 Arr[k-1]++
    A.forEach { item in
        let index = item-1
        if index < N {
            if resultArr[index] < baseValue {
                resultArr[index] = baseValue + 1
            } else {
                resultArr[index] += 1
            }

            if maxValue < resultArr[index] {
                maxValue = resultArr[index]
            }
        } else {
            baseValue = maxValue
        }
    }

    resultArr = resultArr.map {
        if $0 < baseValue {
            return baseValue
        } else {
            return $0
        }
    }

    return resultArr
}

A[K] == N+1 일 때 모든 Value를 바꿔주었는데 이 부분을 하지않고 baseValue를 두어 이를 해결 하였다.

실행시간 O(N+M) 이 되어 100점을 받을 수 있었다.

'Coding Test > Swift' 카테고리의 다른 글

Codility - GenomicRangeQuery  (0) 2020.08.05
Swift 코딩테스트  (0) 2020.07.31
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함