๊ด€๋ฆฌ ๋ฉ”๋‰ด

Coding Planet

level1. ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ Java ๋ณธ๋ฌธ

๐ŸŽ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

level1. ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ Java

jhj.sharon 2023. 10. 5. 11:15
๋ฐ˜์‘ํ˜•

โœจ ๋ฌธ์ œ

๐Ÿ’ป์ฝ”๋“œ

 

import java.util.Map;
import java.util.HashMap;

public class Solution {
    public String[] solution(String[] players, String[] callings) {
        // players ๋ฐฐ์—ด ๋‚ด์—์„œ ํŠน์ • ์„ ์ˆ˜์˜ ํ˜„์žฌ ์œ„์น˜๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•œ map ์ƒ์„ฑ
        Map<String, Integer> playerPosition = new HashMap<>();
        for (int i = 0; i < players.length; i++) {
            playerPosition.put(players[i], i);
        }
        
        // ๊ฐ calling์— ๋”ฐ๋ผ ์„ ์ˆ˜๋“ค์˜ ์œ„์น˜๋ฅผ ๋ณ€๊ฒฝ
        for (String calling : callings) {
            int position = playerPosition.get(calling);
            // ์„ ์ˆ˜์˜ ์œ„์น˜์™€ ๋ฐ”๋กœ ์•ž์˜ ์„ ์ˆ˜์˜ ์œ„์น˜๋ฅผ swap
            swap(players, position, position - 1);
            // playerPosition ์—…๋ฐ์ดํŠธ
            playerPosition.put(players[position], position);
            playerPosition.put(players[position - 1], position - 1);
        }
        
        return players;
    }
    
    // ๋ฐฐ์—ด์˜ ๋‘ ์œ„์น˜์˜ ์›์†Œ๋ฅผ swapํ•˜๋Š” helper ํ•จ์ˆ˜
    private void swap(String[] arr, int i, int j) {
        String temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

๐Ÿ‘ฉ‍๐Ÿ’ป ํ’€์ด ๋ฐฉ๋ฒ•

  • ์œ„ ๋ฌธ์ œ๋Š” ๋ฐฐ์—ด๋งŒ ์ด์šฉํ•ด์„œ ์ถฉ๋ถ„ํžˆ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๋ฐฐ์—ด์„ ์ด์šฉํ•  ๊ฒฝ์šฐ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ์„ ์ˆ˜์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„์•ผ ํ•˜๋ฏ€๋กœ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(n)์ด ๋œ๋‹ค. ํ•˜์ง€๋งŒ HashMap์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์„ ์ˆ˜ ์ด๋ฆ„์ด ํ‚ค๋กœ ๋“ค์–ด๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ํ˜„์žฌ์œ„์น˜๋ฅผ O(1)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ์ฐพ์„ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.
  • ๋ฌธ์ œ์˜ ์กฐ๊ฑด์—์„œ ์•Œ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ( 2 ≤ callings์˜ ๊ธธ์ด ≤ 1,000,000)  callings ๊ธธ์ด๊ฐ€ ๋งค์šฐ ๊ธธ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ด์ ์„ ์ฃผ์˜ํ•ด์•ผํ•œ๋‹ค.

๐Ÿ”” ๋Š๋‚€์ 

  • calling์— ๋”ฐ๋ผ ์„ ์ˆ˜ ์œ„์น˜๋ฅผ ๋ฐ”๊ฟ€ ๋•Œ swap๋ฉ”์„œ๋“œ๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ๋‹ค์‹œ HashMap์— ์—…๋ฐ์ดํŠธํ•˜์ง€ ์•Š์•„ ์‹คํŒจํ–ˆ์—ˆ๋‹ค...
๋ฐ˜์‘ํ˜•
Comments