Golang Leetcode 219. Contains Duplicate II.go

2019-04-12 11:34:31 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412916

思路

用hash表保存出现过的元素,找到的时候判断一下距离

code

代码语言:javascript复制
func containsNearbyDuplicate(nums []int, k int) bool {
	if len(nums) < 2 {
		return false
	}
	m := make(map[int]int)
	for i, v := range nums {
		val, ok := m[nums[i]]
		if ok {
			if val k >= i {
				return true
			}
		}
		m[v] = i
	}
	return false
}

0 人点赞