在哈希表上添加元素

我正在阅读 Grokking Algorithms,它给了我一个我无法在 Javascript 上复制的 Hash Map 的例子......这很简单,我唯一不知道的是如何将 ID 的值添加到“投票”变量


var canVote = function(id) {

  var voted = {};

  for(let i = 0; i < id.length; i++) {

    if(id in voted) {

      console.log("ID already voted!");

    } else {

      voted[id] = id;

      console.log("Voted successufully!")

    }

  }

}


var id = [10, 20, 20]

canVote(id);


慕尼黑8549860
浏览 63回答 1
1回答

犯罪嫌疑人X

Hash表的思想是查找一个值是否存在于O(1). 但是,如果你遍历一个n元素数组,你显然最终会进行n不断的操作,这会导致O(n).此外,您使用的逻辑在循环迭代中存在缺陷。我在下面的代码中修改了它。请检查。var canVote = function(id) {&nbsp; &nbsp; var voted = {};&nbsp; &nbsp; id.forEach(voteId=>{&nbsp; &nbsp; &nbsp; &nbsp; if(voted[voteId]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("ID already voted!");&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; voted[voteId] = voteId;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Voted successufully!")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })}var id = [10, 20, 20]canVote(id);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript