题目:
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
示例 1: 输入: nums = [1,2,3,1], k= 3 输出: true
解题思路:
1 set判断是否存在重复数字
2 index查出数字的下标
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
length = len(nums)
if length <= 0 or nums==None or k<=0:
return False
if len(set(nums ) )>= length:
return False
for i in range(length-1):
num = nums.count(nums[i])
tmp = nums[i]
while num > 1:
start =nums.index(tmp)
nums[start] = '1'
end = nums.index(tmp)
if end - start <=k:
return True
else:
num = num-1
return False