[Java] ํ๋ก๊ทธ๋๋จธ์ค - ํธํ ๋ฐฉ ๋ฐฐ์
[๋ฌธ์ ]
https://school.programmers.co.kr/learn/courses/30/lessons/64063
ํ๋ก๊ทธ๋๋จธ์ค
์ฝ๋ ์ค์ฌ์ ๊ฐ๋ฐ์ ์ฑ์ฉ. ์คํ ๊ธฐ๋ฐ์ ํฌ์ง์ ๋งค์นญ. ํ๋ก๊ทธ๋๋จธ์ค์ ๊ฐ๋ฐ์ ๋ง์ถคํ ํ๋กํ์ ๋ฑ๋กํ๊ณ , ๋์ ๊ธฐ์ ๊ถํฉ์ด ์ ๋ง๋ ๊ธฐ์ ๋ค์ ๋งค์นญ ๋ฐ์ผ์ธ์.
programmers.co.kr
[ํ์ด]
ํด๋น ๋ฌธ์ ๋ ๋ฐฉ์ ๋ฐฐ์ ํ๋ฉฐ, ํด๋น ๋ฐฉ ๋ค์์ผ๋ก ์ฌ ์ ์๋ ๋น๋ฐฉ์ ์ฐ๊ฒฐํด ๊ณ์ ๊ฐฑ์ ํด์ฃผ๋ฉฐ ํ์ดํ๋ ๋ฌธ์ ์ ๋๋ค.
Map<Long, Long>์ ์ฌ์ฉํ์๋๋ฐ, ํด๋น Map์ <๋ฐฉ ๋ฒํธ x, x ๋์ ๋ฐฐ์ ๋ ์ ์๋ ๋ฐฉ ๋ฒํธ> ํ์์ผ๋ก ์ ์ฅ๋ฉ๋๋ค.
์ ์ถ๋ ฅ ์๋ฅผ ์ดํด๋ณด๋ฉด, ํ์ด ๊ณผ์ ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
room_number : [1,3,4,1,3,1]
- room_number๋ฅผ ํ์ํ๋ฉฐ ๋ฐฉ์ ๋ฐฐ์ ํด answer[]์ ๊ฐฑ์ ํฉ๋๋ค.
- ๋ง์ฝ, ํด๋น ๋ฐฉ ๋ฒํธ๋ฅผ ํค๋กํ๋ ๊ฐ x์ด map์ ์กด์ฌํ์ง ์๋๋ค๋ฉด ์์ง ๋ฐฐ์ ๋์ง ์์๋ฐฉ์ด๋ฏ๋ก x๋ฅผ ๋ฐฐ์ ํ๊ณ , map์ <x, x+1> ๊ฐ์ ์ ์ฅํฉ๋๋ค. ( ์ดํ x๊ฐ ๋ค์ด์์๋ x+1์ ๋ฐฐ์ ํด์ฃผ๊ธฐ ์ํด์)
- ๋ง์ฝ, ํด๋น ๋ฐฉ ๋ฒํธ๋ฅผ ํค๋ก ํ๋ ๊ฐ x๊ฐ map์ ์กด์ฌํ๋ค๋ฉด, ์ด๋ฏธ x๋ ๋ฐฐ์ ๋์ผ๋ฏ๋ก while๋ฌธ์ ํตํด map์์ ์์ง ๋ฐฐ์ ๋์ง ์์ ๋ฐฉ์ ์ฐพ์์ ํด๋น ๋ฐฉ๋ฒํธ y๋ฅผ ๋ฐฐ์ ํฉ๋๋ค. ์ด๋, map์ ํตํด ๊ฑฐ์ณ์จ ๋ฐฉ๋ฒํธ๋ค์ ๋ชจ๋ y+1๋ก ๊ฐฑ์ ํด์ค๋๋ค.
์์ ๊ฐ์ ๊ณผ์ ์ ๊ฑฐ์น๊ณ ๋๋ฉด map์ ๋ณํ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
{1=2}
{1=2, 3=4}
{1=2, 3=4, 4=5}
{1=3, 2=3, 3=4, 4=5}
{1=3, 2=3, 3=6, 4=6, 5=6}
{1=7, 2=3, 3=7, 4=6, 5=6, 6=7}
- 1๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> map.get(1)์ null์ด๋ฏ๋ก 1๋ฒ ๋ฐฐ์ ํ map.get(1) = 2๋ก ๊ฐฑ์
- 3๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> map.get(3)์ null์ด๋ฏ๋ก 3๋ฒ ๋ฐฐ์ ํ map.get(3) = 4๋ก ๊ฐฑ์
- 4๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> map.get(4)์ null์ด๋ฏ๋ก 4๋ฒ ๋ฐฐ์ ํ map.get(4) = 5๋ก ๊ฐฑ์
- 1๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> ์ด๋ฏธ ๋ฐฐ์ ๋ ๋ฐฉ์ด๋ฏ๋ก, map์ ๋ฐ๋ผ๊ฐ๋ฉด 1->2->null ์ด๋ฏ๋ก 2๋ฒ๋ฐฉ ๋ฐฐ์ ํ
map.get(1) = 3, map.get(2) = 3์ผ๋ก ๊ฐ๊ฐ ๊ฐฑ์ - 3๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> ์ด๋ฏธ ๋ฐฐ์ ๋ ๋ฐฉ์ด๋ฏ๋ก, map์ ๋ฐ๋ผ๊ฐ๋ฉด 3->4->5-> null ์ด๋ฏ๋ก 5๋ฒ๋ฐฉ ๋ฐฐ์ ํ
map.get(3) = 6, map.get(4) = 6, map.get(5) = 6์ผ๋ก ๊ฐ๊ฐ ๊ฐฑ์ - 1๋ฒ ๋ฐฉ ๋ฐฐ์ ์๊ตฌ -> ์ด๋ฏธ ๋ฐฐ์ ๋ ๋ฐฉ์ด๋ฏ๋ก, map์ ๋ฐ๋ผ๊ฐ๋ฉด 1->3->6->null ์ด๋ฏ๋ก 6๋ฒ๋ฐฉ ๋ฐฐ์ ํ
map.get(1) = 7, map.get(3) = 7, map.get(6) = 7์ผ๋ก ๊ฐ๊ฐ ๊ฐฑ์
๋ฐ๋ผ์ answer = [1,3,4,2,5,6]์ด ๋ฉ๋๋ค.
[์ฝ๋]
import java.util.*;
class Solution {
public static Map<Long, Long> map = new HashMap<Long,Long>();
public long[] solution(long k, long[] room_number) {
long[] answer = new long[room_number.length];
for(int i=0;i<room_number.length;i++) {
long num = room_number[i];
if(map.get(num) == null) {
answer[i] = num;
map.put(num, num + 1);
} else {
ArrayList<Long> list = new ArrayList<Long>();
while(map.get(num) != null) {
list.add(num);
num = map.get(num);
}
answer[i] = num;
map.put(num, num + 1);
for(Long l:list) {
map.put(l,num + 1);
}
}
System.out.println(map);
}
return answer;
}
}