# 219. Contains Duplicate II

## 刷题内容

• https://leetcode.com/problems/contains-duplicate-ii/

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false


## 解题方案

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if k == 0:
return False
if k >= len(nums):
return len(nums) != len(set(nums))
for i in range(len(nums)-k):
for j in range(1, k+1):
if nums[i] == nums[i+j]:
return True
for i in range(len(nums)-k, len(nums)):
for j in range(i+1, len(nums)):
if nums[i] == nums[j]:
return True
return False


class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if k == 0:
return False
if k >= len(nums):
return len(nums) != len(set(nums))
for i in range(len(nums)-k):
if len(nums[i:i+k+1]) != len(set(nums[i:i+k+1])):
return True
return len(nums[-k:]) != len(set(nums[-k:]))


class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
lookup = {}
for i in range(len(nums)):
if nums[i] not in lookup:
lookup[nums[i]] = i
else:
if i - lookup[nums[i]] <= k:
return True
else:
lookup[nums[i]] = i
return False