Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 베스트앨범 #197

Closed
hwangJi-dev opened this issue Apr 12, 2023 · 0 comments
Closed

[Algorithm] 베스트앨범 #197

hwangJi-dev opened this issue Apr 12, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Apr 12, 2023

💬 문제

https://school.programmers.co.kr/learn/courses/30/lessons/42579


💬 Idea

  1. struct 구조체를 만들어 음악 정보를 저장해준다.
  2. genreDict를 만들어 재생횟수를 저장해준다
  3. 최대 재생횟수를 가지는 장르 순위대로 베스트앨범을 채운다.
    1. 가장 많이 재생된 장르
    2. 해당 장르 중 가장 많이 재생된 노래
      1. 재생횟수가 같다면 고유번호 낮은 순으로 정렬

💬 풀이

import Foundation

struct Music {
    var genre: String
    var playCnt: Int
    var index: Int
}

func solution(_ genres:[String], _ plays:[Int]) -> [Int] {
    var genreDict: [String: Int] = [:]
    var musics: [Music] = []
    var album: [Int] = []
    
    for (idx, genre) in genres.enumerated() {
        musics.append(Music(genre: genre, playCnt: plays[idx], index: idx))
        if genreDict[genre] == nil {
            genreDict[genre] = plays[idx]
        } else {
            genreDict[genre]! += plays[idx]
        }
    }
    
    musics = musics.sorted(by: {
        if $0.playCnt == $1.playCnt {
            return $0.index < $1.index
        } else {
            return $0.playCnt > $1.playCnt
        }
    })
    
    for i in genreDict.sorted(by: { $0.value > $1.value }) {
        let music = musics.filter({ $0.genre == i.key }).map({ $0.index })
        if music.count >= 2 {
            album += music[0...1]
        } else {
            album.append(music[0])
        }
    }
    
    return album
}

소요시간 : 23분


💬 더 나은 방법?

  • 구조체 배열을 담는 변수를 제거하고 Dictionary에 튜플 형식으로 응용하여 사용
struct Music {
    var playCnt: Int
    var index: Int
}

func solution(genres:[String], plays:[Int]) -> [Int] {
    var genreDict: [String: ([Music], Int)] = [:]
    var album: [Int] = []
    
    for (idx, genre) in genres.enumerated() {
        if genreDict[genre] != nil {
            genreDict[genre]!.0.append(Music(playCnt: plays[idx], index: idx))
            genreDict[genre]!.1 += plays[idx]
        } else {
            genreDict[genre] = ([Music(playCnt: plays[idx], index: idx)], plays[idx])
        }
    }
    
    for i in genreDict.sorted(by: { $0.value.1 > $1.value.1 }) {
        let music = i.value.0.sorted(by: {
            return ($0.playCnt == $1.playCnt) ? $0.index < $1.index : $0.playCnt > $1.playCnt
        }).map({ $0.index })
        album += music.count >= 2 ? music[0...1] : [music[0]]
    }
    
    return album
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant