문제
https://school.programmers.co.kr/learn/courses/30/lessons/42579
내가 푼 풀이
[장르: (인덱스: Int, 재생수: Int)]의 딕셔너리 한개와, [장르: 총재생수] 딕셔너리를 구현하여 만들었습니다.
주어진 jenres 문자열 배열을 위 딕셔너리 두개로 먼저 파싱한 뒤, 총 재생수가 많은 순으로 정렬하여 해당 장르를 접근하였습니다.
[장르: (인덱스: Int, 재생수: Int)]의 value에서 재생수가 많은 순으로 정렬한 다음, 장르 key값으로 (인덱스: Int, 재생수: Int) 튜플 value에 접근하여 가장 재생수가 높은 두개의 곡을 뽑아서 배열에 저장한 뒤 리턴하였습니다.
코드로 구현하면 다음과 같습니다.
import Foundation
func solution(_ genres:[String], _ plays:[Int]) -> [Int] {
var played = [String: [(index: Int, plays: Int)]]()
var totalPlayedGenres = [String: Int]()
var album = [Int]()
for i in 0..<genres.count {
let genre = genres[i]
let playCount = plays[i]
if played[genre] == nil {
played[genre] = [(index: i, plays: playCount)]
totalPlayedGenres[genre] = playCount
} else {
played[genre]!.append((index: i, plays: playCount))
totalPlayedGenres[genre]! += playCount
}
}
let sortedGenres = totalPlayedGenres.sorted { $0.value > $1.value }
sortedGenres.forEach { element in
let songs = played[element.key]!.sorted{ $0.plays > $1.plays}
for i in 0..<songs.count {
album.append(songs[i].index)
if i == 1 { break }
}
}
return album
}