leetcode 219. Contains Duplicate II

twisted-fate發表於2019-05-26
# brute force pesudo code

find all equal pairs , compare gap with k 組合問題

for i in nums
    for j=i+1 in nums
        if nums[i]==nums[j]
            gap=j-i
            if gap<=k
                return true

return false
//brute force
func containsNearbyDuplicate(nums []int, k int) bool {
    lens:=len(nums)
    for i:=0;i<=lens-1;i++{
        for j:=i+1;j<=lens-1;j++{
            if nums[i]==nums[j] {
                gap:=j-i

                if gap<=k {
                    return true
                }
            }
        }
    }
    return false
}

圖片

覆盤: 滑動視窗還是分析的太慢太亂 , 錯誤也很多


# sliding window   有錯誤的虛擬碼

make a map[int]int
l=0 r=0  map[0]=nums[0]
while r!=endIndex
    if r+1-l<=k && nums[r+1] in map
        return true
    else
        if r+1-l<k
            move r one step forward and save into map
        if r+1-l==k
            move l one step and delete from map
            move r one step and save to map

return false

leetcode 219. Contains Duplicate II

func containsNearbyDuplicate(nums []int, k int) bool {
    if len(nums)==0 {
        return false
    }
if k==0 {
        return false
    }
    map1:=make(map[int]int)
    l:=0
    r:=0
    map1[nums[0]]=0

    for r<len(nums)-1 {
        inMap:=false
        if _,ok:=map1[nums[r+1]];ok {
            inMap=true
        }

        if r+1-l<=k && inMap {
            return true
        } else {
            if r-l<k-1 {
                r++
                map1[nums[r]]=r
                continue
            }
            if r-l==k-1 {
                delete(map1,nums[l])
                l++

                r++
                map1[nums[r]]=r
                continue
            }
        }
    }

    return false

}

leetcode 219. Contains Duplicate II

參考 bobo 老師的解法寫的 , 十分簡潔 , 不過不太好懂

func containsNearbyDuplicate(nums []int, k int) bool {
    myMap:=make(map[int]int)
    for i:=0;i<len(nums);i++ {
        if _,ok:=myMap[nums[i]];ok {
            return true
        }
        myMap[nums[i]]=i

        if len(myMap) ==k+1 {
            delete(myMap,nums[i-k])
        }
    }

    return false

}

leetcode 219. Contains Duplicate II

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章