소프트웨어에 대한 모든 것

LeetCode 풀기 - 973. K Closest Points to Origin 본문

알고리즘/LeetCode

LeetCode 풀기 - 973. K Closest Points to Origin

앤테바 2021. 12. 26. 13:52
반응형

973. K Closest Points to Origin

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

문제)

솔루션1)

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        distances = []
        for i, point in enumerate(points):
            distances.append([i, pow(point[0],2)+ pow(point[1], 2)])
        distances = sorted(distances, key=lambda x: x[1])
        return [points[distances[i][0]] for i in range(k)]

솔루션2) heapq.nsmallest() 사용

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        return heapq.nsmallest(k, points, key=lambda x: pow(x[0], 2) + pow(x[1], 2))
반응형
Comments