오늘 풀어본 문제는
프로그래머스 순위검색 입니다.
import java.util.*;
class Solution {
static HashMap<String, ArrayList<Integer>> map;
public int[] solution(String[] info, String[] query) {
int[] answer = new int[query.length];
map = new HashMap<>();
for(String in : info)
{
String [] infoArr = in.split(" ");
comb("",0,infoArr);
}
int queryIdx = 0;
for(String q : query)
{
String str = q.replace(" and ","");
String [] tmp = str.split(" ");
Collections.sort(map.get(tmp[0]));
answer[queryIdx++] = binarySearch(tmp[0],Integer.parseInt(tmp[1]));
}
return answer;
}
static void comb(String str,int depth,String [] arr) {
if (depth == 4) {
int score = Integer.parseInt(arr[4]);
if (map.containsKey(str)) map.get(str).add(score);
else {
ArrayList<Integer> tmp = new ArrayList<>();
tmp.add(score);
map.put(str, tmp);
}
return;
}
comb(str + "-", depth + 1, arr);
comb(str + arr[depth], depth + 1, arr);
}
static int binarySearch(String query, int score)
{
if(!map.containsKey(query)) return 0;
ArrayList<Integer> tmpList = map.get(query);
int start = 0, end = tmpList.size()-1;
while(start <= end)
{
int mid = (start + end) / 2;
if(score > tmpList.get(mid)) start = mid + 1;
else end = mid - 1;
}
return tmpList.size() - start;
}
}
이분탐색 문제입니다.
입력받은 지원자의 정보들로 만들어 질 수 있는 모든 경우의 수를 조합 알고리즘을 사용하여 map에 담아줍니다.
각 경우의 수로 조합된 문자열이 key값 , 점수가 value가 됩니다.
조합이 완료되면 이분탐색을 위해 점수를 기준으로 데이터를 정렬하고,
이분탐색을 통해 갯수를 answer배열에 리턴해줍니다.
오늘은 코딩테스트를 앞두고 있어 카카오 기출문제를 풀어봤습니다!
효율성이 계속 안나와서 고민이었는데, 다른분의 코드를 보고 많이 배운 문제였습니다.
전처리 과정에서 데이터를 정렬할 때부터 각 언어와 지원분야 등을 하나의 문자열로 하여 따로 저장했더니 비교연산에서 너무 복잡해졌었는데, 애초에 공백을 제거하고 한 문자열로 붙여놓으니 비교도 간편하고 좋았습니다!
평소 구글링 안하려고 이악물고 노력하는 편인데, 가끔은 고집부리지말고 시간과 정신건강을 지키기 위해 다른자료도 좀 참고해야겠네요😅
이코드 런타임 에러랑 시간초과나요