K points closest to the origin leetcode-973-

Subject description:

 

 

 

 May refer to: title 215

Method One: Sort

class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        points.sort(key = lambda P: P[0]**2 + P[1]**2)
        return points[:K]

Quick Exhaust + Divide and Conquer:

class Solution:
     DEF kClosest (Self, Points: List [List [int]], K: int) -> List [List [int]]:
         # calculating Euclidean distances 
        Distance = the lambda I: Points [I] [0 ] Points ** 2 + [I] [. 1] ** 2 DEF Work (I, J, K):
             IF I> J:
                 return # record initial value 
            OI, OJ = I, J
             # take sentinel value is the leftmost 
            pivot = Distance (OI)
             the while I =! J:
                 the while I <J and Distance (J)> = 
                    J
        
        
             Pivot:- =. 1
                 the while I <J and Distance (I) <= Pivot: 
                    I + =. 1
                 IF I < J:
                     # exchange value 
                    Points [I], Points [J] = Points [J], Points [I] 
                
            # exchange sentinel 
            Points [I], Points [OI] = Points [OI], Points [I] 
            
            # recursive 
            IF K <= I - OI +. 1 :
                 # left half sort 
                Work (OI, I -. 1 , K)
             the else :
                 # right half sequence
                work(i + 1, oj, K - (i - oi + 1))
                
        work(0, len(points) - 1, K)
        return points[:K]

Method three: heap sort

from heapq import heappush, heappop 

class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        queue = []
        distance = lambda x: points[x][0]**2 + points[x][1]**2
        length = len(points)
        for i in range(length):
            heappush(queue, (distance(i), points[i]))
        res = []
        for i in range(K):
            res.append(heappop(queue)[1])
        return res

 

Guess you like

Origin www.cnblogs.com/oldby/p/11641068.html