새소식

Test/Coding Tests

[Programmers] 최빈값 구하기

  • -

func solution(_ array:[Int]) -> Int {
        var dictionary = [Int: Int]()
    var key = 0
    var count = 0
    
    for i in array {
        if dictionary.contains {$0.key == i} {
            dictionary[i]! += 1
        } else {
            dictionary[i] = 1
        }
    }
    for (i, j) in dictionary {
        if j == dictionary.values.max() {
            count += 1
            key = i
        }
    }
    return count == 1 ? key : -1
}
728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.