使用对象优先于数组删除重复项。

javascript
阅读 39 收藏 0 点赞 0 评论 0

remove-dupes-object-true-On.js
function removeDupes(str) {
    const uniqueChars = []
    const chars = {}

    for(let i=0; i < str.length; i++){ // O(n)
        const thisItem = str[i]
        
        // I'm checking if inside of the object Chars there is 
        // the letter with a true value which means that it found 
        // that element into the object so does not fo anything
        // else it add it to the uniqueChars array and also
        // add it into the object to search for it int the loop
        // And I do that because searching trough an object is instantaneous O(1)
        // rather than use includes which lopps trough the whole array

        if(chars[thisItem] === true){ // O(1)
            continue
        }else{
            uniqueChars.push(thisItem)
            chars[thisItem] = true
        }
    }
    return uniqueChars.join('')
}

console.log(
  //removeDupes('abcd'),          // abcd
  removeDupes('aabbccdd'),      // abcd
  //removeDupes('abababcdcdcd'), // abcd

)

// Time:  O(n)
// Space: O(n)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号