题目:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
解法:
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
def containsNearbyDuplicate(self, nums, k):
sorted_nums = nums[:]
sorted_nums.sort()
if len(nums)<=1:
return False
for index,value in enumerate(sorted_nums):
if index<len(sorted_nums)-1 and value==sorted_nums[index+1]:
index1 = nums.index(value)
nums.remove(value)
index2 = nums.index(value)+1
if index2-index1<=k:
return True
return False