【问题标题】:Hash Tables: Ransom Note - Hacker Rank in Javascript哈希表:赎金笔记 - Javascript 中的黑客排名
【发布时间】:2018-07-21 12:40:19
【问题描述】:

我正在准备在 Hacker Rank 上进行 preparation questions 的面试,我想在这方面做得更好。是否有可能得到一些反馈?如何改进我的代码?你是怎么解决this的问题的?

function getCount(array){
    let counts = {}
    for(let word of array){
        let count = counts[word]
        counts[word] = count ? counts[word] + 1: 1;
    }
    return counts
}
// Complete the checkMagazine function below.

function compareNoteMag(note,mag){
    let noteKeys = Object.keys(note)
    let string = 'Yes'
    for(let key of noteKeys){
        if(!mag[key]) string = 'No'
        if(mag[key] < note[key]){
            string = 'No'
        }
    }
     console.log(string)
}

function checkMagazine(magazine, note) {
    let magazineCount = getCount(magazine);
    let noteCount = getCount(note);
    compareNoteMag(noteCount,magazineCount)
};

【问题讨论】:

  • 我不确定,但如果您在 codereview.stackexchange.com 询问这个问题可能会更好
  • 谢谢@Max 我在那里得到了一些很好的答案:D

标签: javascript arrays hashmap


【解决方案1】:

举几个具有时间复杂度的解决方案示例,这可能会有所帮助

解决方案 1: 这对于几个测试用例来说是可以的,但你会失败一些测试用例,如下所示 随着杂志数量和笔记长度增加的限制,它将无法在hackerank https://www.hackerrank.com/environment设置的时间限制内执行

function checkMagazine(magazine, note) {

    
    for (var i = 0; i <= note.length; i++) { //O(n)
        for (var j = 0; j <= magazine.length; j++) { //O(n)
            if (note[i] == magazine[j]) {
                
                magazine.splice(magazine.indexOf(magazine[j]), 1) //O(n)
                note.splice(note.indexOf(note[i]), 1) //O(n)


            }
        }

    }
    let result = (note.length > 0) ? "No" : "Yes"
    console.log(result)
}

解决方案 2: 比解决方案 1 更好,但这也会导致某些测试用例失败

    function checkMagazine(magazine, note) {
    let result = "Yes"
    note.forEach((n) => { //O(n)
        if (magazine.includes(n)) { //O(n)
            magazine.splice(magazine.indexOf(n), 1) //O(n) 
        }
        else {
            result = "No"
            return
        }

    })
    console.log(result)
}

解决方案 3: 比上面两个更好,这应该通过所有测试用例,因为这里我们使用 js 对象哪种 HashTable,因此访问元素成本 u O(1)

function checkMagazine(magazine, note) {
     let hash_mag = {}
     let result = "Yes"

     magazine.forEach((m)=>{ //O(n)
         hash_mag[m] = hash_mag[m] ? hash_mag[m]+1 : 1
     })

    note.forEach((n) => { //O(n)
        if (hash_mag[n]>0) { //O(1)
            hash_mag[n] =  hash_mag[n] - 1 //O(1)
        }
        else {
            result = "No"
            return
        }

    })
    console.log(result)
}

【讨论】:

  • 我想出了与您的第三个解决方案类似的解决方案,但我的解决方案未能通过某些测试用例,而您的解决方案却没有。不幸的是,我无权访问失败的特定测试用例。你能帮我理解我的解决方案和你的解决方案之间的区别吗?我的解决方案在这里:github.com/boxcarcoder/test/blob/main/Hash%20Table/…
  • 如果您将代码从 table[magazine[i]]++ 更改为 ++table[magazine[i]] 或 table[,杂志循环中的唯一区别是前后增量magazine[i]]+1 那么你的解决方案应该可以工作
猜你喜欢
  • 2019-02-21
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-08-04
  • 2023-02-11
相关资源
最近更新 更多