Skip to content

Commit af74fcf

Browse files
committed
K Closest Points to Origin
1 parent 5077980 commit af74fcf

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ gem 'rspec'
44
gem 'ruby-debug-ide'
55
gem 'debase'
66
gem 'pry-byebug'
7+
gem 'algorithms'

Gemfile.lock

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
GEM
22
remote: https://rubygems.org/
33
specs:
4+
algorithms (0.6.1)
45
byebug (11.1.1)
56
coderay (1.1.2)
67
debase (0.2.4.1)
@@ -35,6 +36,7 @@ PLATFORMS
3536
ruby
3637

3738
DEPENDENCIES
39+
algorithms
3840
debase
3941
pry-byebug
4042
rspec

leetcode/k_closest_points_spec.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)