여름의 서재

[프로그래머스] 튜플 (파이썬 & 자바) 본문

알고리즘/프로그래머스

[프로그래머스] 튜플 (파이썬 & 자바)

엉아_ 2021. 12. 10. 00:50
728x90

📕 문제

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

 

코딩테스트 연습 - 튜플

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

 

💡 풀이법

- Python

from collections import defaultdict

def solution(s):
    set_dict = defaultdict(int)
    flag = False
    for i in s:
        if i.isdigit():
            if not flag:
                number = i
                flag = True
            else:
                number += i
        else:
            if flag:
                set_dict[int(number)] += 1
                flag = False
                
    number_count = sorted(set_dict.items(), key=lambda x:x[1], reverse=True)
    answer = [num for num, cnt in number_count]
    return answer

s = "{{4,2,3},{3},{2,3,4,1},{2,3}}"
print(solution(s))

 

- Java

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

class Solution {
    public int[] solution(String s) {
        String[] arr = s.substring(2, s.length() - 2).split(",|\\},\\{");
        HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();

        for (String i:arr) {
            int j = Integer.parseInt(i);
            if (hashMap.containsKey(j)) {
                hashMap.put(j, hashMap.get(j)+1);
            } else {
                hashMap.put(j, 1);
            }
        }
        
        List<Integer> numberList = new ArrayList<Integer>(hashMap.keySet());
        Collections.sort(numberList, (v1, v2) -> (hashMap.get(v2) - hashMap.get(v1)));
 
        int[] answer = new int[numberList.size()];
        for (int i = 0; i < numberList.size(); i++)
            answer[i] = numberList.get(i);
        return answer;
    }
}
Comments