JavaScript算法题-哈希

80 阅读1分钟

3. 无重复字符的最长子串

hash数组 -> 快速寻找数组中是否存在目标元素

let hash =[]
let s="abcabcbb"
hash[s[0]] ++
console.log(hash); // [ a: NaN ]
hash[s[0]] = 0
hash[s[0]] ++ 
console.log(hash); // [ a: 1 ]

->

if(hash[s[0]] > -1) hash[s[0]] ++
else hash[s[0]] = 0 
console.log(hash); 

题解-hash

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let hash = [] , res = 0, nowl = 0
    // 特殊情况 s=" "
    if(s.length === 1) return 1
    for(let  i = 0 ; i < s.length ; i++){ 
        for(let j = i; j < s.length ; j++){
            if(hash[s[j]]>0){
                res = Math.max(res,nowl)
                nowl = 0
                hash = []
                break
            }else{
                nowl ++ 
                hash[s[j]] = 1
            }
        }  
    }
    return res
};

题解-滑动窗口

1. 两数之和

image.png

题解

hash数组存储已经尝试过的元素及其对应下标

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let hash = [] , curNum , targetNum
    for(let i = 0 ; i < nums.length ; i++){
        curNum = nums[i]
        targetNum = target - nums[i]
        if(hash[targetNum] != undefined) return [i,hash[targetNum]]
        else hash[curNum] = i
    }
};