fastest way to determine if an element is in a sorted array

后端 未结 5 1335
长情又很酷
长情又很酷 2021-01-05 06:42

I have an array of sorted ints with a 1,000 or more values (could be up to 5000+). I need to write a function that receives an int and returns a bool based on the element be

5条回答
  •  太阳男子
    2021-01-05 07:36

    If doing lookups more than once, migrate to a map-like object.

    var fastLookup = {};
    mySortedArray.forEach(function(i){fastLookup[i]=true)});
    
    //Each time:
      if (fastLookup[key]===true){ //do thing
      }

提交回复
热议问题