240321 도넛과 막대 그래프

Jongleee·2024년 3월 21일
0

TIL

목록 보기
526/737
public int[] solution(int[][] edges) {
	int[] answer = new int[4];
	Map<Integer, int[]> nodeMap = initializeNodeMap(edges);
	int maxNode = getMaxNode(edges);

	for (int node = 1; node <= maxNode; node++) {
		if (nodeMap.containsKey(node)) {
			int[] degrees = nodeMap.get(node);
			if (degrees[0] >= 2 && degrees[1] == 0)
				answer[0] = node;
			else if (degrees[0] == 0)
				answer[2]++;
			else if (degrees[0] >= 2 && degrees[1] >= 2)
				answer[3]++;
		}
	}

	answer[1] = nodeMap.get(answer[0])[0] - (answer[2] + answer[3]);

	return answer;
}

private Map<Integer, int[]> initializeNodeMap(int[][] edges) {
	Map<Integer, int[]> nodeMap = new HashMap<>();
	for (int[] edge : edges) {
		int from = edge[0], to = edge[1];
		nodeMap.putIfAbsent(from, new int[] { 0, 0 });
		nodeMap.putIfAbsent(to, new int[] { 0, 0 });

		nodeMap.get(from)[0]++;
		nodeMap.get(to)[1]++;
	}
	return nodeMap;
}

private int getMaxNode(int[][] edges) {
	int maxNode = -1;
	for (int[] edge : edges) {
		maxNode = Math.max(maxNode, Math.max(edge[0], edge[1]));
	}
	return maxNode;
}

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

0개의 댓글