diff --git a/NeetCode/k-closest-points-to-origin/step1.py b/NeetCode/k-closest-points-to-origin/step1.py new file mode 100644 index 0000000..44f6a04 --- /dev/null +++ b/NeetCode/k-closest-points-to-origin/step1.py @@ -0,0 +1,34 @@ +""" +Question: 1m + How is the size of k? + How is the lenght of points? + 1 <= points.length < 10^4 +Discussion: 3m + n: length of points + + sort + time: O(nlogn) + space: O(n) + + priority queue + time: O(n) + space: O(k) +Coding: 7m +Simple Test: 4m + (1, 1), (3, 3) k: 1 +""" + +import heapq + +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + pq = [] + for i in range(len(points)): + distance = points[i][0] ** 2 + points[i][1] ** 2 + heapq.heappush(pq, (distance, i)) + + res = [] + for _ in range(k): + _, index = heapq.heappop(pq) + res.append((points[index][0], points[index][1])) + return res diff --git a/NeetCode/k-closest-points-to-origin/step2.py b/NeetCode/k-closest-points-to-origin/step2.py new file mode 100644 index 0000000..02ed8c5 --- /dev/null +++ b/NeetCode/k-closest-points-to-origin/step2.py @@ -0,0 +1,19 @@ +""" +enumerate +tuple +""" + +import heapq + +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + pq = [] + for i, (x, y) in enumerate(points): + distance = x ** 2 + y ** 2 + heapq.heappush(pq, (distance, i)) + + res = [] + for _ in range(k): + _, index = heapq.heappop(pq) + res.append(tuple(points[index])) + return res