LeetCode:计算相同数组元素的下标差(Contains Duplicate II)

来源:互联网 发布:拉货搬家软件 编辑:程序博客网 时间:2024/05/29 02:41

题目:

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.

思路:

首先判断数组元素非空非1. 如果为空为1则返回False

判断数组长度是否小于等于k,如果是则看是否有相同元素,没有则返回False,有则返回True

其次用一个辅助字典:关键字为nums[i],为了方便理解,子字典值设为——{“last_index“: 位置}。

那么下次遇到相同元素时,查找它的上次出现位置,计算与当前的距离,最小的一个存入res

遍历整个数组,直到res<k, 返回True。否则返回False。

代码(Python)时间 O(n), 空间 O(n)

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        if len(nums) < 2: return False        if len(nums) <= k: return False if len(set(nums))==len(nums) else True        dic = dict()        res = len(nums)        for i in range(len(nums)):            key = nums[i]            if key not in dic:                dic[key] = {'last_index':i}             else:                res = min(res, i - dic[key]['last_index'])                dic[key]['last_index'] = i                if res <= k: return True        return False


0 0
原创粉丝点击