튜플_복습

하이솝·2026년 8월 4일

2026.08.04

문제 풀이

나의 코드


소요 시간: 1시간 8분
시간 복잡도: O(n2)O(n^2)


import java.util.Map;
import java.util.HashMap;

class Solution {
    public int[] solution(String s) {
        Map<Integer, Integer>map = new HashMap<>();
        
        StringBuilder sb = new StringBuilder();
        sb.append(s.charAt(2));
        
        for (int i = 3; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != '{' && c != '}' && c != ',') { // 숫자일 때,
                sb.append(c);
            }
            if (sb.length() > 0 && (c == '}' || c == ',')) {
                Integer n = Integer.parseInt(sb.toString());
                map.put(n, map.getOrDefault(n, 0) + 1);
                sb.delete(0, sb.length());
            }
        }
        int[] result = new int[map.size()];
        int idx = 0;
        while(!map.isEmpty()) {
            int maxKey = 0;
            int maxValue = 0;
            
            for (Integer key : map.keySet()) {
                if (map.get(key) > maxValue) {
                    maxKey = key;
                    maxValue = map.get(key);
                }
            }
            map.remove(maxKey);
            result[idx++] = maxKey;
        }
        return result;
    }
}

AI 코드


시간 복잡도: O(n2)O(n^2)


코드 분석

num * 10 + (c - '0')을 이용하여 int만을 이용해 숫자 누적

merge(num, 1, Integer::sum)put(n, getOrDefault(n, 0) + 1)과 동일

reading이라는 boolean 변수를 두어 숫자가 저장되어 있는지 판별


import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] solution(String s) {
        Map<Integer, Integer> freq = new HashMap<>();

        int num = 0;
        boolean reading = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                num = num * 10 + (c - '0');   // 자릿수 누적
                reading = true;
            } else if (reading) {             // 숫자가 끝나는 지점
                freq.merge(num, 1, Integer::sum);
                num = 0;
                reading = false;
            }
        }

        return freq.entrySet().stream()
                   .sorted((a, b) -> b.getValue() - a.getValue())  // 등장 횟수 내림차순
                   .mapToInt(Map.Entry::getKey)
                   .toArray();
    }
}

문제 풀이 후기

간단한 변수 추가로 코드를 훨씬 더 간단하게 만드는 방법을 사용하니
코드가 훨씬 더 깔끔하게 보이고 가독성이 좋아졌다.

마지막에 정렬 하는 부분은 strea()을 이용하여 정렬했는데,
해당 부분이 이해가 잘 안돼서 반복적으로 의식하고 해당 코드를 사용할 수 있을 때 앞으로 사용해야겠다는 생각이 들었다.

0개의 댓글