-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
💬 문제
https://school.programmers.co.kr/learn/courses/30/lessons/42579
💬 Idea
- struct 구조체를 만들어 음악 정보를 저장해준다.
- genreDict를 만들어 재생횟수를 저장해준다
- 최대 재생횟수를 가지는 장르 순위대로 베스트앨범을 채운다.
- 가장 많이 재생된 장르
- 해당 장르 중 가장 많이 재생된 노래
- 재생횟수가 같다면 고유번호 낮은 순으로 정렬
💬 풀이
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
}