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