코딩테스트 연습 - 숫자 짝꿍 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr

1. 아이디어
초기에 문제에 접근한 방식은 아래와 같이 이중 루프를 통해 각 배열에 접근하여 일일이 비교하는 형태로 작성하였다.
for(int i=0; i<X.length(); i++){
for(int j=0; j<Y.length(); j++){
if(X.charAt(i) == Y.charAt(j)){
if(!checkX[i] && !checkY[j]){
checkX[i] = true;
checkY[j] = true;
break;
}
}
}
}
그러나 결국 시간 초과가 발생하였고, String 연산자를 반복하여 작성한 것도 마찬가지로 시간초과의 원인이 되었다.
따라서 이중 루프의 크기를 최소화 하고자 하였고, StringBuilder 를 통해 String 연산의 시간도 줄였다.
2. 코드
import java.util.*;
class Solution {
public String solution(String X, String Y) {
int[] xarr = new int[10];
int[] yarr = new int[10];
int[] result = new int[10];
for(int i=0; i<X.length(); i++){
int n = X.charAt(i)-48;
xarr[n]++;
}
for(int i=0; i<Y.length(); i++){
int n = Y.charAt(i)-48;
yarr[n]++;
}
for(int i=0; i<10; i++){
if(xarr[i]>0 && yarr[i]>0){
int n = Math.min(xarr[i],yarr[i]);
result[i]+=n;
}
}
ArrayList<Character> resultList = new ArrayList<>();
for(int i=0; i<10; i++){
if(xarr[i]>0 && yarr[i]>0){
for(int j=0; j<result[i]; j++)
resultList.add((char)(i+48));
}
}
Collections.sort(resultList, Collections.reverseOrder());
if(resultList.isEmpty())
return "-1";
else if(resultList.get(0) == '0')
return "0";
else{
StringBuilder sb = new StringBuilder();
for(int i=0; i<resultList.size(); i++)
sb.append(resultList.get(i));
return sb.toString();
}
}
}'코딩 테스트(Coding Test) > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] 삼각 달팽이 (0) | 2024.11.20 |
|---|---|
| [프로그래머스] 교점에 별 만들기 (1) | 2024.11.20 |
| [프로그래머스] A로 B만들기 (0) | 2023.09.01 |
| [프로그래머스] 최빈값 구하기 (0) | 2023.07.20 |
| [프로그래머스] 공원 산책 (1) | 2023.05.28 |