231025 호텔 방 배정

Jongleee·2023년 10월 25일
0

TIL

목록 보기
399/737
public long[] solution(long k, long[] roomNumbers) {
	int n = roomNumbers.length;
	if (n > k)
		return new long[] { -1 };

	Map<Long, Long> nextRoomMap = new HashMap<>();
	long[] assignedRooms = new long[n];

	for (int i = 0; i < n; i++) {
		assignedRooms[i] = getEmptyRoom(roomNumbers[i], nextRoomMap);
		nextRoomMap.put(roomNumbers[i], assignedRooms[i] + 1);
	}

	return assignedRooms;
}

private long getEmptyRoom(long roomNumber, Map<Long, Long> nextRoomMap) {
	if (!nextRoomMap.containsKey(roomNumber)) {
		nextRoomMap.computeIfAbsent(roomNumber, a -> a + 1);
		return roomNumber;
	}
	long emptyRoom = getEmptyRoom(nextRoomMap.get(roomNumber), nextRoomMap);
	nextRoomMap.put(roomNumber, emptyRoom + 1);
	return emptyRoom;
}

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

0개의 댓글