lintcode练习-1319. 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.

您在真实的面试中是否遇到过这个题?  是

样例

Given nums = [1,2,1], k = 0, return false.

实现代码:

两种思路

一种是将所有坐标都存储起来,然后依次比较

一种是修改坐标,和最近的比较

class Solution:
    """
    @param nums: the given array
    @param k: the given number
    @return:  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
    """
    '''
    def containsNearbyDuplicate(self, nums, k):
        # Write your code here
        _hash = {}
        for i, key in enumerate(nums):
            if key not in _hash:
                _hash[key] = [i]
            else:
                for n in _hash[key]:
                    print(i - n )
                    if i - n <= k  :
                        return True
                _hash[key] += [i]

        return False
    '''

    def containsNearbyDuplicate(self, nums, k):
        # Write your code here
        _hash = {}
        for i, key in enumerate(nums):
            if key not in _hash:
                _hash[key] = i
            else:
                if i - _hash[key] <= k:
                    return True
                else:
                    _hash[key] = i
        return False

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81235313