Skip to content

Instantly share code, notes, and snippets.

@kevinmichaelchen
Created October 14, 2014 16:00
Show Gist options
  • Select an option

  • Save kevinmichaelchen/4b6572e3282158a0e7c0 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmichaelchen/4b6572e3282158a0e7c0 to your computer and use it in GitHub Desktop.
Remove duplicates from array in linear time
#!/usr/bin/ruby
# Remove duplicates from array in linear time
arr = [6,2,4,2,4,6]
puts "#{arr.size} elements in original array:"
puts arr.inspect
# keep track of what we see
seen = {}
# the new array
arr2 = Array.new(0)
arr.each do |k|
if seen.has_key? k
arr2.push k
else
seen[k] = true
end
end
puts arr2.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment