New Solution
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
numdict = dict()
for i in range(len(nums)):
if nums[i] not in numdict.keys():
numdict[nums[i]] = [i]
else:
for j in range(len(numdict[nums[i]])):
if abs(numdict[nums[i]][j] - i) <= k:
return True
numdict[nums[i]].append(i)
return False
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
numdict = dict()
for i in range(len(nums)):
if nums[i] not in numdict.keys():
numdict[nums[i]] = i
else:
if abs(numdict[nums[i]] - i) <= k:
return True
numdict[nums[i]] = i
return False
This question asks me: given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that … … . .
There are a ton of constraints, and I feel like these are two different problems.
One of them is the original contains duplicate problem, which simply asked to return true if any value occurs twice in an array.
To solve this, I created a dictionary, saving the occurrences of each number, and thereafter just traversing through the dictionary and returning true if any number was greater han 1
References
https://leetcode.com/problems/contains-duplicate-ii/description/