码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-03-14 20:23:30      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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进行相似的处理。

 

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

标签:

原文地址:http://www.cnblogs.com/aksdenjoy/p/5276945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!