algorithm - Find keys of the 3 largest values in a Javascript Object with O(n) complexity? -
say have object such as:
let objtocheck = { a: 2, b: 5, c: 9, d: 33, e: 4, f: 8, g: 3, h: 10 };
how go returning keys of 3 largest values in ascending order, in case be: [ 'c', 'h', 'd' ]
, in linear time? evidently need loop through entire object once compare values, i'm having troubling coming solution doesn't involve nested loops believe o(n²). here solution looks far:
function findbig3(obj){ const res = []; const largest = object.values(obj).sort((a,b) => {return b-a}).slice(0,3); (let key in obj){ largest.foreach( (val) => { if (obj[key] === val) res.push(key); }); } return res; }
i imagine need declare 3 variables, such big1
, big2
, big3
, , loop through object type of comparison check , reassign appropriate, i'm struggling implementation.
this algorithm runs in o(n).
function getthreelargestkeys(obj){ var k1, k2, k3; var v1, v2, v3; v1 = v2 = v3 = -infinity; // o(1) var insertkey = function(key){ var value = obj[key]; // note 1 // note 2 if(value >= v1){ v3 = v2; v2 = v1; v1 = value; k3 = k2; k2 = k1; k1 = key; }else if(value >= v2){ v3 = v2; v2 = value; k3 = k2; k2 = key; }else if(value >= v3){ v3 = value; k3 = key; } }; // o(n) for(var key in obj){ // note 3 insertkey(key); } return [k1, k2, k3]; }
https://jsfiddle.net/derekl/pzatq729/
please not copy-paste code right homework solution. rewrite code once understand it.
note:
- this assumes object lookup o(1). depends on how implemented in interpreter, lower o(log n).
- these conditionals can optimized. leave practice reader.
- normally should check if key owned object instance, here assume input object not inherited
object.prototype
.
Comments
Post a Comment