|
| 1 | +# https://leetcode.com/problems/k-closest-points-to-origin/ |
| 2 | +# https://www.educative.io/courses/grokking-the-coding-interview/3YxNVYwNR5p |
| 3 | +# https://medium.com/basecs/learning-to-love-heaps-cef2b273a238 |
| 4 | +# https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/tutorial/ |
| 5 | +# https://www.youtube.com/watch?v=t0Cq6tVNRBA |
| 6 | +# Runtime: 220 ms, faster than 100.00% of Ruby online submissions for K Closest Points to Origin. |
| 7 | +# Memory Usage: 12.1 MB, less than 100.00% of Ruby online submissions for K Closest Points to Origin. |
| 8 | + |
| 9 | +# O(n log n) |
| 10 | +def k_closest(points, k) |
| 11 | + points.sort_by{|x, y| x*x + y*y}.first(k) |
| 12 | +end |
| 13 | + |
| 14 | +# http://kanwei.github.io/algorithms/classes/Containers/MinHeap.html |
| 15 | +require 'algorithms' |
| 16 | +include Containers |
| 17 | + |
| 18 | +# O(n log n + k log k) = O(n log n) |
| 19 | +def k_closest2(points, k) |
| 20 | + heap = MinHeap.new |
| 21 | + points.each do |x, y| |
| 22 | + d = x*x + y*y |
| 23 | + heap.push(d, [x, y]) |
| 24 | + end |
| 25 | + ans = [] |
| 26 | + k.times do |
| 27 | + ans << heap.pop |
| 28 | + end |
| 29 | + ans |
| 30 | +end |
| 31 | + |
| 32 | +describe '#k_closest' do |
| 33 | + it 'finds k closest points to origin (0,0)' do |
| 34 | + expect(k_closest([[0,1],[1,0]], 2)).to eq [[0,1], [1,0]] |
| 35 | + expect(k_closest([[1,3],[-2,2]], 1)).to eq [[-2,2]] |
| 36 | + |
| 37 | + now = Time.now |
| 38 | + expect(k_closest([[3,3],[5,-1],[-2,4]], 2)).to eq [[3,3],[-2,4]] |
| 39 | + puts Time.now - now |
| 40 | + # 1.2e-05 secs |
| 41 | + |
| 42 | + now = Time.now |
| 43 | + expect(k_closest2([[3,3],[5,-1],[-2,4]], 2)).to eq [[3,3],[-2,4]] |
| 44 | + puts Time.now - now |
| 45 | + # 8.0e-05 secs (heap is slower) |
| 46 | + end |
| 47 | +end |
0 commit comments