Created
September 29, 2011 18:01
-
-
Save nwjsmith/1251435 to your computer and use it in GitHub Desktop.
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
function HashMap () { | |
this._items = {}; | |
this.length = 0; | |
} | |
HashMap.prototype.get = function (key) { | |
if (key === null || typeof this._items[this._hash(key)] === undefined) { | |
return null; | |
} | |
return this._items[this._hash(key)]; | |
}; | |
HashMap.prototype.put = function (key, value) { | |
this._items[this._hash(key)] = value; | |
this.length++; | |
}; | |
HashMap.prototype._hash = function (value) { | |
if (value instanceof Object) { | |
return (typeof value) + " " + (value._hash || (value._hash = ++this._counter)); | |
} else { | |
return (typeof value) + " " + value.toString(); | |
} | |
}; | |
HashMap.prototype._counter = 0; | |
function pairWithSum(sum, randoms) { | |
var deltas = new HashMap(), delta, i, l; | |
for (i = 0, l = randoms.length; i < l; i++) { | |
if (deltas.get(randoms[i])) { | |
return [ randoms[i], deltas.get(randoms[i]) ]; | |
} | |
deltas.put(sum - randoms[i], randoms[i]); | |
} | |
} | |
pairWithSum(98, [100, 20, -2, 30, 4]); // => [-2, 100] |
thuva
commented
Sep 29, 2011
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment