leetcode Day50 剑指专项61-65

132 阅读1分钟

532. 数组中的 k-diff 数对

var findPairs = function(nums, k) {
    let res=new Set()
    let visited=new Set()
    for(let i of nums){
        if(visited.has(i-k)){
            res.add(i-k)
        }
        if(visited.has(i+k)){
            res.add(i)
        }
        visited.add(i)
    }
    return res.size
};

剑指 Offer II 061. 和最小的 k 个数对

var kSmallestPairs = function(nums1, nums2, k) {
    let res=[]
    for(let i of nums1){
        for(let j of nums2){
            res.push([i,j])
        }
    }
    res.sort((a,b)=>(a[0]+a[1])-(b[0]+b[1]))
    return res.slice(0,k)
};

剑指 Offer II 063. 替换单词

var replaceWords = function(dictionary, sentence) {
    let root={}
    for(let w of dictionary){
        let cur=root
        for(let s of w){
            if(cur[s]===undefined){
                cur[s]={}
            }
            cur=cur[s]
        }
        cur.isend=true
    }
    let resArr=sentence.split(' ')
    for(let i=0;i<resArr.length;i++){
        let word=resArr[i]
        let str=''
        let cur=root
        for(let s of word){
            if(cur.isend){
                resArr[i]=str
                break
            }
            if(!cur[s]){
                break
            }
            str+=s
            cur=cur[s]
        }
    }
    return resArr.join(' ')
};

剑指 Offer II 065. 最短的单词编码

var minimumLengthEncoding = function(words) {
    let res=0
    let root={}
    words.sort((a,b)=>b.length-a.length)
    for(let w of words){
        let flag=false
        let cur=root
        for(let i=w.length-1;i>=0;i--){
            if(!cur[w[i]]){
                cur[w[i]]={}
                flag=true
            }
            cur=cur[w[i]]
        }
        if(flag)res+=w.length+1
    }
    return res
};