본문 바로가기
알고리즘 & 자료구조/Leetcode

[Leetcode 973] - K Closest Points to Origin w/ Python

by Zenu 2024. 4. 16.

 

 

 

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).

 

 

[x, y]의 좌표가 들어있는 배열이 주어졌고, k라는 숫자도 주어졌을때

Origin (0,0)에서 가장 가까운 k개의 숫자를 리턴하는 문제

 

가장 가까운 좌표를 리턴할때 순서는 상관 없다

 

 

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

 

 

 


 

 

 

 

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.

 

 

 

 


 

 

 

 

heapq로 저장을 할때 (거리, x 좌표, y 좌표)로 값을 저장한다

 

 

거리를 정할때 정수/음수 상관 없이 제곱하면 다 정수가 되기 때문에

굳이 루트를 사용하지 않고 계산이 가능하다

 

 

이를 통해 가장 낮은 숫자 k개를 빼서 ans 배열에 저장하고

리턴을 해서 문제를 풀었다

 

 

class Solution:
    def kClosest(self, points, k):
        heap = []
        ans = []

        for point in points:
            dist = (point[0] ** 2) + (point[1] ** 2)
            heapq.heappush(heap, (dist, point[0], point[1]))
        
        for _ in range(k):
            dist, x, y = heapq.heappop(heap)
            ans.append([x, y])
        
        return ans

 

 

 

 

반응형