Problem Definition:
Given an array of integers and a integer K, find out whether there there is
Distinct indices i and J in the array such that nums[i] = Nums[j] and the difference between i and J are at the most K.
Solution 1:o (n^2) (report timeout)
1 defContainsnearbyduplicate (Nums, k):2n=Len (nums)3 ifn*k==0:4 returnFalse5I=06 whileI<n-1:7J=18 whilej<=K:9 if(i+j) > (n-1):Ten Break One ifnums[i]==nums[i+J]: A returnTrue - Else: -J+=1 theI+=1 - returnFalse
Solution 2: In the space for time, in the process of the array of values and values of the index in the formation of key-value pairs in the dictionary (dict), the time complexity of the dictionary query is O (1).
1DefContainsnearbyduplicate (self, nums, K):2 n =Len (nums)3If n*k==0:4ReturnFalse5 D ={}6For IInchRange (N):7If Nums[i]not in D: 8 D[nums[i]] = I 9 else< Span style= "color: #000000;" >:10 diff = ABS (d[nums[i]]-i) 11 if diff <= K:12 return True13 else:14 D[nums[i]] = I 15 return False
leetcode#219 Contains Duplicate II