Contains Duplicate II
Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such that nums[i] = nums[j] and the absolute difference betweeniandjis at mostk.
Example 1:
Example 2:
Example 3:
Solution
Using HashSet
O(min(n,k))) space - O(n) time
基本思想是维持一个k大小的窗口,用hashset记录其中的数,如果hashset的大小超过了k就从中删除最远的那个数,如果hashset出现有当前数字,那么就返回true
@san89kalp Explanation: It iterates over the array using a sliding window. The front of the window is at i, the rear of the window is k steps back. The elements within that window are maintained using a Set. While adding new element to the set, if add() returns false, it means the element already exists in the set. At that point, we return true. If the control reaches out of for loop, it means that inner return true never executed, meaning no such duplicate element was found.
https://leetcode.com/problems/contains-duplicate-ii/discuss/61372/Simple-Java-solution
HashMap
O(n) space - O(n) time
Last updated