Leetcode: Contains Duplicate II

来源:互联网 发布:mac桌面图标消失 编辑:程序博客网 时间:2024/05/16 04:56

Question

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 difference between i and j is at most k.

Show Tags
Show Similar Problems


Solution

Analysis

A map is created to record whether an element appeared before as well as its ind.

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        if nums==[] or len(nums)==1:            return False        dictin = {}        for ind, elem in enumerate(nums):            if elem in dictin:                preind = dictin[elem]                if abs(ind-preind)<=k:                    return True                else:                    dictin[elem] = ind            else:                dictin[elem] = ind         return False
0 0
原创粉丝点击