题目描述:
Given an array of integers and an integer k, return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
题目大意:
给定一个整数数组nums与一个整数k,当且仅当存在两个不同的下标i和j满足nums[i] = nums[j]并且| i - j | <= k时返回true,否则返回false。
解题思路:
使用dict保存数组中数字的下标
Python代码:
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
def containsNearbyDuplicate(self, nums, k):
numDict = dict()
for x in range(len(nums)):
idx = numDict.get(nums[x])
if idx >= 0 and x - idx <= k:
return True
numDict[nums[x]] = x
return False
本文链接:http://bookshadow.com/weblog/2015/05/29/leetcode-contains-duplicate-ii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。