728x90
https://school.programmers.co.kr/learn/courses/30/lessons/178871?language=csharp
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
실패 코드
using System;
public class Solution {
public string[] solution(string[] players, string[] callings) {
string temp;
foreach(string s in callings) {
for(int i = 0; i < players.Length; i++) {
if(players[i] == s) {
if(i == 0) {
break;
}
temp = players[i];
players[i] = players[i-1];
players[i-1] = temp;
break;
}
}
}
string[] answer = players;
return answer;
}
}
직관적으로 문제 자체를 그대로 코드에 옮겼다.
내 이름이 불렸다면? 앞 사람과 내 위치를 변경하고
만약 내가 1등이라면? break;되도록 작성했다.
머리를 전혀 쓰지않고 코드를 짰더니
시간 초과가 발생했다.
제한사항을 보면 배열의 길이가 50,000, 1,000,000이다.
배열의 인덱스를 찾는 것은 최악의 경우의 O(n^2)의 시간복잡도가 발생할 수 있다.
그래서 생각을 해봤는데, 예전에 이런 문제를 해시로 풀었던 기억이 났다.
성공 코드
using System;
using System.Collections.Generic;
public class Solution {
public string[] solution(string[] players, string[] callings) {
string[] answer = new string[players.Length];
// HashMap
Dictionary<string, int> dicPlayer = new Dictionary<string, int>();
Dictionary<int, string> dicRank = new Dictionary<int, string>();
// dicPlayers, dicRank 초기화
for(int i = 0; i < players.Length; i++) {
dicPlayer[players[i]] = i; // dicPlayers[이름 : 등수(0부터 시작)]
dicRank[i] = players[i]; // dicRank[등수(0부터 시작) : 이름]
}
foreach(string call in callings) {
// 만약 1등이면 순서 안바꾸고
if(dicPlayer[call] == 0) {
break;
}
// 1등이 아니면 앞뒤 순서 바꾸기
int rank = dicPlayer[call]; // 이름 불린 사람의 등수
string name = dicRank[rank]; // 이름 불린 사람의 순위
string frontName = dicRank[rank-1]; // 앞사람의 이름
dicPlayer[call] = rank - 1;
dicRank[rank - 1] = name;
int frontRank = dicPlayer[frontName];
dicPlayer[frontName] = frontRank + 1;
dicRank[frontRank + 1] = frontName;
}
for(int i = 0; i < players.Length; i++) {
answer[i] = dicRank[i];
}
return answer;
}
}
통과했다!!
헷.. 기분 좋다..
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 신고 결과 받기(C#) (0) | 2023.12.27 |
---|---|
[프로그래머스] 개인정보 수집 유효기간(C#) (0) | 2023.12.27 |
[프로그래머스] 해시 - 전화번호 목록(feat. python) (0) | 2023.09.14 |
[프로그래머스] 해시 - 포켓몬(feat. python) (0) | 2023.09.07 |
[Python] 프로그래머스 - 해시 - 완주하지 못한 선수 (0) | 2023.08.30 |