N

(Leet Code JS)K Closest Points to Origin 본문

Leet Code 알고리즘

(Leet Code JS)K Closest Points to Origin

naeunchan 2021. 11. 27. 19:44
728x90
반응형

https://leetcode.com/problems/k-closest-points-to-origin/

 

K Closest Points to Origin - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

array 배열과 answer 배열을 선언.

 

points 배열을 순회하면서 array에 유클리드 거리와 인덱스를 넣어준다.

유클리드 거리와 인덱스가 저장된 array 배열을 거리의 오름차순으로 정렬.

 

k개 만큼 answer에 답을 넣어주면 된다.

 

/**
 * @param {number[][]} points
 * @param {number} k
 * @return {number[][]}
 */
const kClosest = (points, k) => {
    const array = [];
    const answer = [];
    
    for(let i = 0; i < points.length; i++){
        array.push([Math.sqrt(points[i][0] ** 2 + points[i][1] ** 2), i]);
    }
    
    array.sort((a, b) => a[0] - b[0]);
    
    for(let i = 0; i < k; i++){
        answer.push(points[array[i][1]]);
    }
    
    return answer;
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code JS)Minesweeper  (0) 2021.12.21
(Leet Code JS)Reorganize String  (0) 2021.11.27
(Leet Code JS)Rearrange Words in a Sentence  (0) 2021.11.20
(Leet Code JS)Count and Say  (0) 2021.11.16
(Leet Code JS)Number of Islands  (0) 2021.11.14