Python实现"存在重复元素||"的一种方法

给定一个整数数组和一个整数k,查找数组中是否存在两个不同索引i和j,满足nums[i]=nums[j],并且i-j的绝对值最大(小于等于k)为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

1:借助字典判断数组中相等的元素和计算索引的绝对值

def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        numDic = {}
        for index, num in enumerate(nums):
            if num not in numDic:
                numDic[num] = index
            else:
                if index-numDic[num]<=k:
                    return True
                numDic[num] = index   #更新同数值的下标数值
        return False

算法题来自:https://leetcode-cn.com/problems/contains-duplicate-ii/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82783685