๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์•Œ๊ณ ๋ฆฌ์ฆ˜

[2019 ์นด์นด์˜ค ๊ฐœ๋ฐœ์ž ๊ฒจ์šธ ์ธํ„ด์‹ญ] ํ˜ธํ…” ๋ฐฉ ๋ฐฐ์ •

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/64063

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

์†Œ์Šค์ฝ”๋“œ

import java.util.Arrays;
import java.util.HashMap;

class Solution {

    HashMap<Long, Long> rooms;

    public long[] solution(long k, long[] room_number) {

        rooms = new HashMap<>();

        return Arrays.stream(room_number)
                        .map(this::findRoom)
                        .toArray();
    }

    public long findRoom(long num) {

        if(!rooms.containsKey(num)) {
            rooms.put(num, rooms.getOrDefault(num+1, num+1));
            return num;
        }

        long next = findRoom(rooms.get(num));

        rooms.put(num, next);
        return next;
    }

}

 

ํšŒ๊ณ 

 ๋ฌธ์ œ๋ฅผ ๋ณด๊ณ  Union-Find๊ฐ€ ๋– ์˜ฌ๋ž๋‹ค. ์ž…๋ ฅ๊ฐ’์ด ํฌ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐ์—ด ๋Œ€์‹  ํ•ด์‹œ๋งต์œผ๋กœ <์˜ˆ์•ฝ ๋œ ๋ฐฉ ๋ฒˆํ˜ธ : ๋‹ค์Œ ๋ฐฉ ๋ฒˆํ˜ธ>์˜ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ , ๋‹ค์Œ ๋ฐฉ ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์„ ๋•Œ ์žฌ๊ท€๋ฅผ ํ†ตํ•ด ๊ณ„์†ํ•ด์„œ ๋งต์„ ์—…๋ฐ์ดํŠธ ํ•ด์ฃผ์—ˆ๋‹ค.