on-internet
← Community

How to minimize number of lookups in a Hash?

Stack Overflow ·

say you want to find the first duplicate in an array. you could do something like this: cnt = {}; [ 11, 22, 77, 22, 33 ].each_with_index { |x,i| j = cnt[x]; ## <1> break [x, j, i] if j cnt[x] = i ## <2> } #=> [ 22, 1, 3 ] this is O(n) as long a Ruby Hash is O(1) for lookup and insert. but still it does lookup two times ( <1>, <2>). Is there a way to avoid it? something like this: cnt = {} some_array.each_with_index { |x,i| j = cnt.exchange( x, i ); break [x, j, i] if j } Yes, I could easily implement such a method: def exchange( k, val ) old, self[k] = self[k], val return old end but this woul

Comments

Sign in or sign up to comment and upvote.

No comments yet.