본문 바로가기
알고리즘/프로그래머스 LV.3

LV.3 프로그래머스 베스트앨범

by 호롤롤로루야 2021. 9. 23.

LV.3 프로그래머스 베스트앨범

1. 문제 링크

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

 

코딩테스트 연습 - 베스트앨범

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가

programmers.co.kr

 

2. 문제 해결에 대한 아이디어

. HashMap<String, Integer> hm 에 각 장르 별로 총 몇 번 재생되었는지 저장했다. 

. 그 후, ArrayList<Song> rankshm에 있는 정보를 옮겨왔다.

. ranks를 재생 수를 기준으로 내림차순으로 정렬했다.

. 그 후, ranks를 순회하며 각 노래의 정보를 가지고, genres[]에 동일한 장르가 있는지 찾는다.

      . 동일한 장르가 있는 경우 ArrayList<Song> temp 에 새로운 Song 객체를 만들어 삽입한다.

      . new Song(j, plays[j], genres[j]);

. 삽입이 끝나면 temp를 재생 수를 기준으로 내림차순 정렬한다.

. 그 후, 답 answertemp의 0번째, 1번째 값을 삽입한다. 이때 tempsize가 1이면 1번째 값은 못 넣는다.

 

3. 코드

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Solution {

	static class Song implements Comparable<Song> {
		int no;
		int cnt;
		String genre;

		public Song(int no, int cnt, String genre) {
			super();
			this.no = no;
			this.cnt = cnt;

			this.genre = genre;
		}

		public Song(int cnt, String genre) {
			super();
			this.cnt = cnt;
			this.genre = genre;
		}

		@Override
		public int compareTo(Song o) {
			if (this.cnt < o.cnt) {
				return 1;
			} else if (this.cnt > o.cnt) {
				return -1;
			} else {
				if (this.no < o.no) {
					return -1;
				} else {
					return 1;
				}
			}

		}

	}

	static ArrayList<Song> songs = new ArrayList<>();
	static HashMap<String, Integer> hm = new HashMap<>();
	static ArrayList<Song> ranks = new ArrayList<>();

	public ArrayList<Integer> solution(String[] genres, int[] plays) {
		ArrayList<Integer> answer = new ArrayList<>();
		for (int i = 0; i < genres.length; i++) {
			hm.put(genres[i], hm.getOrDefault(genres[i], 0) + plays[i]);
		}
		for (String key : hm.keySet()) {
			ranks.add(new Song(hm.get(key), key));
		}

		Collections.sort(ranks);

		for (int i = 0; i < ranks.size(); i++) {
			ArrayList<Song> temp = new ArrayList<>();
			for (int j = 0; j < genres.length; j++) {
				if (ranks.get(i).genre.equals(genres[j])) {
					temp.add(new Song(j, plays[j], genres[j]));

				}
			}

			Collections.sort(temp);
			answer.add(temp.get(0).no);
			if (temp.size() > 1)
				answer.add(temp.get(1).no);
		}

		return answer;
	}
}
 

4. 채점 결과

 

5. 느낀 점

. HashMap을 꼭 써야하나 고민이 되었는데 안 써도 구현할 수 있을 것 같다.

. HashMap의 함수 중 getOrDefault(Object key, DefaultValue) 를 요긴하게 써야겠다.

      . key 에 매핑된 value 가 있을 경우 엔 .get(key) 를 반환한다.

      . key 에 매핑된 value 가 없을 경우엔 DefaultValue를 반환한다.

 

'알고리즘 > 프로그래머스 LV.3' 카테고리의 다른 글

프로그래머스 LV.3 네트워크  (0) 2022.01.14

댓글