python leetcode 日记 --Contains Duplicate II --219

题目:

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 jis at most k.

给定一个整形数组和一个整数型数k,找出在这个数组中是否存在两个相同的数,并且这两个数的下标的距离小于k。

        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """

根据题目可知输入为一个list和一个整形,返回值为bool

因为此题不能改变数组,因此最原始的一种办法就是遍历:

 

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        if k==0:
            return False
        while len(nums)>1:
            tem=nums.pop(0)#没那一个数出来比较,原列表少一,减少搜索空间,但减少的很慢,效率很低
            j=self.findLocation(nums,tem,k)
            if j<k and j>=0:
                return True
        return False
    def findLocation(self,L,number,k):
        for item in L:
            if item ==number:
                return L.index(item)
            k-=1
            if k==0:
                return -1
        return -1

但是在提交时发现此种方法无法通过例子list(range(30000)) 15000这个测试,分析发现因为如果数组的数全不一样,那么其复杂度为O(n2)。

在查找解决方法后,学习了python中字典的使用,参考https://leetcode.com/discuss/54123/python-concise-solution-with-dictionary

 

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        dictionary={}
        for key,value in enumerate(nums):
            if value in dictionary and key-dictionary[value]<=k:
                return True
            dictionary[value]=key
        return False

通过使用字典,将算法复杂性变为O(n)

如果使用c++或JAVA,本题则需使用hashtable进行相似的处理。

 

转载于:https://www.cnblogs.com/aksdenjoy/p/5276945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值