Coding/알고리즘
[알고리즘 TIL] 튜플(Java, 자료구조)
kangplay
2025. 6. 4. 18:26
문제
https://school.programmers.co.kr/learn/courses/30/lessons/64065
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
프로그래머스 LV2
설명
단순 구현 문제라서 크게 어려운 것은 없었지만, 정렬을 내가 원하는 기준으로 하기 위해 커스텀하는 과정을 기억하지 못했다. Compartor를 이용해 순서를 지정하는 방법을 기억해두자.
Comparator<ArrayList<Integer>> comparator = new Comparator<>() {
@Override
public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {
return Integer.compare(a.size(), b.size()); // 오름차순 정렬
}
};
구현
static class Solution {
public int[] solution(String s) {
int[] answer;
PriorityQueue<ArrayList<Integer>> pq = new PriorityQueue<>(
Comparator.comparingInt(List::size)
);
String[] inputStrArr = s.split("}");
answer = new int[inputStrArr.length];
for (int i = 0; i < inputStrArr.length; i++) {
ArrayList<Integer> nums = new ArrayList<>();
String str="";
for (int j = 0; j < inputStrArr[i].length(); j++) {
if(inputStrArr[i].charAt(j)=='{') continue;
if(inputStrArr[i].charAt(j)!=',') str+=inputStrArr[i].charAt(j);
else {
if(str.length()>0) nums.add(Integer.parseInt(str));
str="";
}
}
if(str.length()>0) nums.add(Integer.parseInt(str));
if(nums.size()>0) pq.add(nums);
}
int count=0;
while(!pq.isEmpty()){
ArrayList<Integer> nums = pq.poll();
for(int num: answer){
for(int i=0;i<nums.size();i++){
if(nums.get(i)==num) {
nums.remove(i);
break;
}
}
}
answer[count++] = nums.get(0);
}
return answer;
}
}