문제

  • 장르별로 재생 횟수가 많은 두곡을 뽑아 베스트앨범 만들기!
  • 아래 이미지와 같이 우선순위는 이러하다
    1. 속한 노래가 많이 재생된(한 장르의 노래 재생 횟수 합) 장르 먼저 수록
    2. 장르 내에서 많이 재생한 노래 먼저 수록
    3. 재생 횟수 같으면 -> 고유번호 낮은 노래 먼저 수록

풀기 위해 사용한 데이터 구조

sumPlaysByGenre : 장르별 재생된 총 횟수를 저장한 dictionary [String: Int]

  • genres와 plays의 크기가 같다고 했으므로 반복문으로 순회하여 genre 값은 key로, play 값은 value에 추가해준다.

sortedGenres : 장르 종류들이 저장된 리스트 [String]

  • sumPlaysByGenre의 value 내림차순 순으로 sorted 함수로 정렬해준다.

idsByGenre : 장르별 노래 고유 번호 id 리스트를 저장한 dictionary [String: [Int]]

  • sumPlaysByGenre처럼 반복문 순회하여 genre는 key로, i를 int 배열인 value에 새로운 원소로 추가해준다.
  • 정렬된 sortedGenres 를 반복문 순회하여 각 장르 안에서 다시 plays 내림차순 기준으로 id들을 sorted 함수로 정렬해준 후 하나 또는 두곡의 id를 뽑아줄 때 사용한다.

코드

import Foundation

func solution(_ genres:[String], _ plays:[Int]) -> [Int] {
    var sumPlaysByGenre: [String: Int] = [:]        // [genre: 각 장르 총 노래 횟수]
    var idsByGenre: [String: [Int]] = [:]       // [genre: 고유 노래 번호 리스트]
    var sortedGenres: [String] = []     // genre list
    var answer: [Int] = []
    
    // 반복문 순회하여 위 데이터 구조 채우기
    for i in 0..<genres.count {
        if !sortedGenres.contains(genres[i]) {
            sortedGenres.append(genres[i])
            sumPlaysByGenre[genres[i]] = plays[i]
            idsByGenre[genres[i]] = [i]
            
        } else {
            sumPlaysByGenre[genres[i]]! += plays[i]
            idsByGenre[genres[i]]! += [i]
        }
    }
    
    // 장르별 총 노래 횟수 많은 순으로 장르 리스트 정렬
    sortedGenres = sortedGenres.sorted { sumPlaysByGenre[$0]! > sumPlaysByGenre[$1]! }
    
    // 장르 순으로 재생 횟수 높은 하나 또는 두 곡 아이디 answer에 저장
    for genre in sortedGenres {
        let Ids = idsByGenre[genre]!.sorted { plays[$0] > plays[$1] }
        answer.append(Ids[0])
        if Ids.count > 1 { answer.append(Ids[1]) }
    }
    return answer
}

결과

  • 꺄륵

이 문제를 풀면서 되새긴 점

Dictionary 생성 또는 접근은 다르게

  • 새로운 값을 생성할 때는 당연히 존재하지 않으니까 !를 붙여 Unwrapping 할 필요 없음.

    • Dict[a] = 0
      
  • 반대로 존재하는 값에 대해 접근할 때, 그리고 그 값이 무조건 있을 때는 !를 붙여 Unwrapping 해야 함.

    • Dict[a]! = 5
      

Dictionary value 기존 값을 증감(?)시킬 때 표현법

  • int인 value를 ++

    • Dict[a]! += 5
      
  • string인 value에 문자 추가

    • Dict[0]! += "a"
      
  • list인 value에 원소 추가

    • Dict[a]! += [5]