Created
October 14, 2014 16:00
-
-
Save kevinmichaelchen/4b6572e3282158a0e7c0 to your computer and use it in GitHub Desktop.
Remove duplicates from array in linear time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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