-
[문제풀이 후기] LeetCode #3898 - Find the Degree of Each Vertex문제풀이/Leetcode 2026. 4. 17. 17:40
https://leetcode.com/problems/find-the-degree-of-each-vertex/
Find the Degree of Each Vertex - LeetCode
Can you solve this real interview question? Find the Degree of Each Vertex - You are given a 2D integer array matrix of size n x n representing the adjacency matrix of an undirected graph with n vertices labeled from 0 to n - 1. * matrix[i][j] = 1 indicate
leetcode.com
문제 포인트
주요 키워드
Vertex : 각 정점 (node)
Edge : 간선 (두 정점을 연결하는 선)
Degree : 차수 (한 정점에 연결되어 있는 간선의 개수)
요약
n x n 사이즈의 2차원 배열 matrix
matrix[i][j] : Vertex i 와 Vertex j 사이의 Edge 보유 여부 (1 : 보유 / 0 : 미보유) (0 ≤ i, j ≤ n-1)
각 Vertex 별 Degree 를 return 하라기본 상위 코드
const matrix = [ [0, 1, 1], [1, 0, 1], [1, 1, 0], ];첫 번째 시도 (결과 : 성공)
접근 방식
1. 각 열의 요소를 모두 합산
return matrix.map((row, rowIndex) => row.reduce((acc, _, colIndex) => acc + matrix[colIndex][rowIndex], 0), );
규칙
양방향 (서로 연결되어 있음)
=> 각 열의 요소의 합 = 각 행의 요소의 합두 번째 시도 (결과 : 성공)
접근 방식
1. 각 행의 요소를 모두 합산
return matrix.map((row) => row.reduce((acc, value) => acc + value, 0));효과
메모리 : 64 MB -> 63.5 MB (감소)
시간 : 1 ms -> 2 ms (증가)
세 번째 시도 (결과 : 성공)
접근 방식
1. 메서드가 아닌 for 문 사용
const N = matrix.length; const result = Array.from({ length: N }, () => 0); for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { result[i] += matrix[i][j]; } } return result;효과
메모리 : 63.5 MB -> 62.9 MB (감소)
시간 : 2 ms -> 3 ms (증가)후기
LeetCode 첫 Review