Skip to content

Latest commit

 

History

History
53 lines (35 loc) · 1.52 KB

219-contains-duplicate-ii.md

File metadata and controls

53 lines (35 loc) · 1.52 KB

219. Contains Duplicate II - 存在重复元素 II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

题目标签:Array / Hash Table

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 48 ms N/A
class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        info = {}
        for i, num in enumerate(nums):
            if num in info and i - info[num] <= k:
                return True
            else:
                info[num] = i
        return False