문제 내용
Star Network에서 center를 찾아라
접근 방법
2개 이상의 Nodes를 이웃하고 있는 점은 단 하나이다.
아무 두점이나 찾아서 2번 나온 값이 답이다.
var findCenter = function(edges) {
return edges[0][0] === edges[1][0] || edges[0][0] === edges[1][1] ? edges[0][0] : edges[0][1];
};
그런데 만약에 Start Networks인데 Center는 하나이지만, 다른 Nodes들도 서로를 이웃할 수 있다면 어떻게될까?
이 경우는 아래와 같이 모든 Points에 대한 Count를 해서 최고로 많은 Count가 나온 값을 답으로 하면 된다.
var findCenter = function(edges) {
let map = new Map();
let max = 0;
let maxNum = 0;
for(let [start,end] of edges){
map.set(start, ~~map.get(start)+1);
map.set(end, ~~map.get(end)+1);
let startCount = map.get(start);
let endCount = map.get(end);
if(startCount < endCount){
if(maxNum < endCount){
max = end;
maxNum = endCount;
}
}else if(endCount < startCount){
if(maxNum < startCount){
max = start;
maxNum = startCount;
}
}
}
return max;
};
728x90
반응형
'Problem Solving' 카테고리의 다른 글
990. Satisfiability of Equality Equations (0) | 2021.07.22 |
---|---|
Average Selling Price (0) | 2021.07.20 |
Edit Distance (Levenshtein 알고리즘) (0) | 2021.07.07 |
One Edit Distance (0) | 2021.07.05 |
The Skyline Problem (0) | 2021.06.30 |