hash去重及应用-【leetcode219-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.

二、

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        d = {}
        for i in range(len(nums)):
	        if nums[i] in d:
		        j = d[nums[i]]
		        if i-j <= k:
			        return True
	        d[nums[i]] = i #前i个数去重
        return False


你可能感兴趣的:(hash去重及应用-【leetcode219-Contains Duplicate II】)