![[Java] 달리기 경주 - Lv1 프로그래머스](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fba1GAe%2Fbtr8tC54yk0%2Fe4RsKWRTiL0LeSxnrrkRzk%2Fimg.png)
[Java] 달리기 경주 - Lv1 프로그래머스코딩테스트/프로그래머스2023. 4. 7. 12:23
Table of Contents
728x90
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/178871
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
players와 callings의 length가 각 50,000 / 1,000,000으로 단순 이중반복문으로 풀면 시간초과가 뜨겠다 싶어서 Map으로 풀었다.
Map<String, Integer> map1 = new HashMap<>();
Map<Integer, String> map2 = new HashMap<>();
for(int i=0; i<players.length; i++) {
map1.put(players[i], i);
map2.put(i, players[i]);
}
for(int i=0; i<callings.length; i++) {
if(map1.containsKey(callings[i])) {
String before = map2.get(map1.get(callings[i])-1);
int beforeN = map1.get(before);
map2.put(map1.get(callings[i])-1, callings[i]);
map2.put(map1.get(callings[i]), before);
map1.put(before, beforeN+1);
map1.put(callings[i], beforeN);
}
}
Map두개를 서로 왔다갔다하며 등수를 변동해주면 끝
아래는 전체코드
import java.util.HashMap;
import java.util.Map;
class Solution {
public String[] solution(String[] players, String[] callings) {
Map<String, Integer> map1 = new HashMap<>();
Map<Integer, String> map2 = new HashMap<>();
for(int i=0; i<players.length; i++) {
map1.put(players[i], i);
map2.put(i, players[i]);
}
for(int i=0; i<callings.length; i++) {
if(map1.containsKey(callings[i])) {
String before = map2.get(map1.get(callings[i])-1);
int beforeN = map1.get(before);
map2.put(map1.get(callings[i])-1, callings[i]);
map2.put(map1.get(callings[i]), before);
map1.put(before, beforeN+1);
map1.put(callings[i], beforeN);
}
}
String[] answer = new String[map2.size()];
for(int i=0; i<answer.length; i++) {
answer[i] = map2.get(i);
}
return answer;
}
}
728x90
300x250
@mag1c :: 꾸준히 재밌게
2023.04 ~ 백엔드 개발자의 기록
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!