First, based on nums, add numbers to build a new array.

Then, sort the new array.

Finally, go though the new array to check if there are duplicate elements.

class Solution(object):

def containsNearbyDuplicate(self, nums, k):

if (len(nums)==1):

return False

newNums=list()

for i in range(len(nums)):

newNums.append((i,nums[i]))

newNums=sorted(newNums, key=lambda newNums : newNums[1])

print (newNums)

for i in range(len(nums)-1):

if (newNums[i][1]==newNums[i+1][1]):

if abs(newNums[i][0]-newNums[i+1][0])<=k:

return True

return False