Publish:

ํƒœ๊ทธ: , , , , ,

์นดํ…Œ๊ณ ๋ฆฌ:

img_3.png

๋ฌธ์ œ

๋ฌธ์ œ ๋งํฌ

img_3.png

์„ค๋ช…

ํ˜„์žฌ ๋‹ฌ๋ฆฌ๊ธฐ ์ˆœ์„œ๊ฐ€ ๋ฐฐ์—ด๋กœ ๋“ค์–ด์˜ค๊ณ , ์•ž ์„ ์ˆ˜๋ฅผ ์ถ”์›”ํ• ๋•Œ ํ•ด์„ค์ง„์ด ์ด๋ฆ„์„ ๋ถ€๋ฅธ๋‹ค. ํ•ด์„ค์ง„์ด ์ด๋ฆ„์„ ๋ถ€๋ฅธ ์„ ์ˆ˜๊ฐ€ callings ๋ฐฐ์—ด๋กœ ๋“ค์–ด์˜ฌ๋•Œ, ๋ณ€๊ฒฝ๋œ ์ˆœ์œ„๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ๋ฌธ์ œ.

Map ์œผ๋กœ ์„ ์ˆ˜์˜ ์ˆœ์œ„๋ฅผ ๊ณ„์† ๊ด€๋ฆฌํ•˜๋ฉด์„œ callings ์—์„œ ๋ถˆ๋ฆฐ ์„ ์ˆ˜๋ฅผ players ๋ฐฐ์—ด์—์„œ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ๊ณ , Map ์—๋„ ์ˆœ์œ„๋ฅผ ๊ฐฑ์‹ ํ•ด ์ค€๋‹ค. for ๋ฌธ์—์„œ ๊ณ„์† ๋‹ค์Œ ์„ ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ์™€ ๋ฐ˜๋ณต ์ž‘์—…ํ•œ๋‹ค.

Map ์œผ๋กœ ์„ ์ˆ˜์™€ ์ธ๋ฑ์Šค๋ฅผ ๊ด€๋ฆฌํ•˜๊ฒŒ ๋˜๋ฉด ํƒ์ƒ‰์— ์œ ๋ฆฌํ•˜๋‹ค. Integer index = map.get(call); ๋Š” O(1) ์— ๋ฐ”๋กœ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ์–ด ์ „์ฒด ์‹œ๊ฐ„๋ณต์žก๋„๋Š” callings ๋ฐฐ์—ด ํฌ๊ธฐ๋งŒ ๊ณ ๋ คํ•˜๋ฉด ๋œ๋‹ค.

ํ’€์ด

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public String[] solution(String[] players, String[] callings) {
    HashMap<String, Integer> map = new HashMap<>();
    for (int i = 0; i < players.length; i++) {
      String player = players[i];
      map.put(player, i);
    }

    for (String call : callings) {
      Integer index = map.get(call);
      if (index == 0) continue;

      String prev = players[index - 1];
      players[index - 1] = call;
      players[index] = prev;

      map.put(call, index - 1);
      map.put(prev, index);
    }

    return players;
  }
}

Map ์œผ๋กœ ์ธ๋ฑ์Šค ๊ด€๋ฆฌ๋ฅผ ํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ (์‹œ๊ฐ„์ดˆ๊ณผ)

๋งŒ์•ฝ Map ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ž…๋ ฅ ๋ฐฐ์—ด์„ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ์–ด๋–จ๊นŒ?

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
  public String[] solution(String[] players, String[] callings) {
    List<String> list = Arrays.asList(players);
    for (String call : callings) {
      int index = list.indexOf(call);
      if (index == 0)
        continue;
      Collections.swap(list, index, index - 1);
    }
    return players;
  }
}

์ฝ”๋“œ๊ฐ€ ์งง์•„ ๊ฐ€๋…์„ฑ์€ ๋†’์•„์ง€์ง€๋งŒ, list.indexOf(call) ๋ถ€๋ถ„์—์„œ ๋‚ด๋ถ€์ ์œผ๋กœ ์ˆœ์ฐจ์ ์œผ๋กœ ํƒ์ƒ‰ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— O(n) ์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฐ๋‹ค. callings ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ m ์ด๋ผ๊ณ  ํ–ˆ์„๋•Œ, ์ „์ฒด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n * m) ์ด ๋œ๋‹ค.

๋ฌธ์ œ์—์„œ callings ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ์ตœ๋Œ€ 100๋งŒ์ด๊ณ , player ์ตœ๋Œ€ ํฌ๊ธฐ๊ฐ€ 50000 ์ด๋‹ค. (n * m = 500์–ต)

๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ