[Medium] 973. K Closest Points to Origin

문제

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

 

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

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

 

점[i] = [xi, yi]이 X-Y 평면의 점 및 정수 k를 나타내는 점 배열이 주어지면 원점(0, 0)에 가장 가까운 k개의 점을 반환합니다.
X-Y 평면의 두 점 사이의 거리는 유클리드 거리이다.
답변은 어떤 순서로든 반환할 수 있습니다. 정답은 고유한 것으로 보장됩니다(해당 순서는 제외).

 

예시

Example 1:

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.

 

제약 조건

Constraints:

  • 1 <= k <= points.length <= 104
  • -104 < xi, yi < 104

 

해결 과정

points 각각 요소들과 원점 사이의 거리를 구하여 Map에 담는다.

거리를 기준으로 오름차 정렬을 한다. 

k 만큼 result에 값을 담아준다.

 

해결 코드

/**
 * @param {number[][]} points
 * @param {number} k
 * @return {number[][]}
 */
var kClosest = function(points, k) {
    let map = new Map();
    let result = [];
    
    // 거리 구하기
    for(let i in points){
        let dist = Math.sqrt((points[i][0] ** 2) + (points[i][1] ** 2));
        map.set(points[i], dist);
    }
        
    // 오름차순 정렬
    let arr = Array.from(map).sort((a, b) => a[1] - b[1]);
        
    for(let i = 0 ; i < k ; i++){
        result.push(arr[i][0])
    }
    
    return result;
};

'leetCode' 카테고리의 다른 글

429. N-ary Tree Level Order Traversal  (0) 2022.07.05
[Medium] 1630. Arithmetic Subarrays  (0) 2022.07.05
[Medium] Spiral Matrix  (0) 2022.07.01
[Easy] 1886. Determine Whether Matrix Can Be Obtained By Rotation  (0) 2022.06.30
[Medium] Rotate Image  (0) 2022.06.30