Contains Duplicate II
Easy · hash map
You are given a list of integers nums and a non-negative integer k.
Return true if there are two different positions i and j such that nums[i] == nums[j] and the positions are at most k apart, that is |i - j| <= k. Otherwise return false.
Think of a row of lockers with a number on each one: you are asking whether any number appears twice within a stretch of k + 1 neighbouring lockers.
Examples
Example 1
Input: nums = [4, 1, 7, 4], k = 3
Output: true
The two 4s are at positions 0 and 3, which are 3 apart.
Example 2
Input: nums = [4, 1, 7, 4], k = 2
Output: false
The only repeated value is 4, and its two copies are 3 apart, which is more than 2.
Example 3
Input: nums = [5, 6, 5, 6, 8], k = 1
Output: false
Both repeated values are 2 apart. No equal values sit next to each other.
Constraints
- 1 <= len(nums) <= 5000
- -10^9 <= nums[i] <= 10^9
- 0 <= k <= 5000