iOS 개발 공부

[Swift] 베스트앨범 본문

코딩테스트/프로그래머스

[Swift] 베스트앨범

물복딱복준복 2023. 6. 18. 21:28
import Foundation

struct Music {
    let id: Int
    let plays: Int
}

func solution(_ genres:[String], _ plays:[Int]) -> [Int] {
    
    var result: [Int] = []
    var album: [String: [Music]] = [:]
    var totalPlays: [String: Int] = [:]
    
    for index in 0..<genres.count {
        let genre = genres[index]
        let plays = plays[index]
        let music = Music(id: index, plays: plays)
        
        if album[genre] == nil {
            album[genre] = [music]
            totalPlays[genre] = plays
        } else {
            album[genre]!.append(music)
            totalPlays[genre]! += plays
        }
    }
    
    for key in totalPlays.sorted(by: { $0.value > $1.value }).map({ $0.key }) {
        var answer: [Int] = []
        for music in album[key]!.sorted(by: { $0.plays > $1.plays }) {
            if 2 <= answer.count { break }
            answer.append(music.id)
        }
        result += answer
    }
    
    return result
}

 

'코딩테스트 > 프로그래머스' 카테고리의 다른 글

[Swift] 하노이의 탑  (0) 2023.06.20
[Swift] 불량 사용자  (0) 2023.06.19
[Swift] 기지국 설치  (0) 2023.06.18
[Swift] 숫자 게임  (0) 2023.06.18
[Swift] 숫자 카드 나누기  (0) 2023.06.18