C# 알고리즘 코드카타

72. 달리기 경주

잼잼재미 2024. 1. 29. 09:53

 

using System;

public class Solution {
    public string[] solution(string[] players, string[] callings) {
        string[] answer = players;
        
        for(int i = 0; i < callings.Length; ++i)
        {
            Swap(callings[i], answer);
        }
        
        return answer;
    }
    
    public void Swap(string str, string[] answer)
    {
        string temp;
        
        for(int i = 0; i < answer.Length; ++i)
        {
            if(answer[i] == str)
            {
                temp = answer[i-1];
                answer[i-1] = answer[i];
                answer[i] = temp;
                break;
            }
        }
    }
}

 

players 배열 전체를 순회해서 Swap하는 함수를 만들었다. 테스트 실행은 통과했으나 결과 제출에서 4가지가 시간 초과 에러가 났다. 아마도 모든 string 배열을 순회하는 것이 오래 걸리는 것 같다.

 

 

수정 코드

 

using System;
using System.Collections.Generic;

public class Solution {
    public string[] solution(string[] players, string[] callings) {
         Dictionary<string, int> dict = new Dictionary<string, int>();

            for (int i = 0; i < players.Length; i++)
                dict.Add(players[i], i);

            for (int i = 0; i < callings.Length; i++)
            {
                int num = dict[callings[i]]--;
                string str = players[num - 1];

                players[num - 1] = players[num];
                players[num] = str;

                dict[str]++;
            }

            return players;
    }
}

 

Dictionary를 사용해서 빠르게 탐색하도록 했다.

'C# 알고리즘 코드카타' 카테고리의 다른 글

74. 신고 결과 받기  (0) 2024.02.07
73. 공원 산책  (0) 2024.02.02
71. 개인정보 수집 유효기간  (0) 2024.01.25
70. 바탕화면 정리  (0) 2024.01.23
69. 성격 유형 검사하기  (0) 2024.01.19