leedcode 存在重复元素II

自己写的:

from typing import List

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        # 创建一个空字典,用于存储数字及其最近出现的索引
        mydict = {}
        # 获取列表的长度
        n = len(nums)
        
        # 遍历列表
        for i in range(0, n):
            # 如果当前数字不在字典中
            if nums[i] not in mydict:
                # 将当前数字及其索引添加到字典中
                mydict[nums[i]] = i
            else:
                # 如果当前数字已经在字典中,则检查其索引是否在范围内
                # 如果在范围内,返回 True
                if i - mydict[nums[i]] <= k:
                    return True
                else:
                    # 如果不在范围内,则更新字典中当前数字的索引为最新的索引
                    mydict[nums[i]] = i
        
        # 遍历完列表后如果没有找到符合条件的情况,则返回 False
        return False

 

posted @ 2024-03-13 10:07  Junior_bond  阅读(4)  评论(0)    收藏  举报