您的位置:首页 > 大数据 > 人工智能

Leetcode: Contains Duplicate II

2015-08-29 10:26 369 查看

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.

[code]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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: