Leetcode

Contains Duplicate II

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  bool containsNearbyDuplicate(vector<int>& nums, int k) {
    unordered_set<int> seen;

    for (int i = 0; i < nums.size(); ++i) {
      if (!seen.insert(nums[i]).second)
        return true;
      if (i >= k)
        seen.erase(nums[i - k]);
    }

    return false;
  }
};

JAVA

class Solution {
  public boolean containsNearbyDuplicate(int[] nums, int k) {
    Set<Integer> seen = new HashSet<>();

    for (int i = 0; i < nums.length; ++i) {
      if (!seen.add(nums[i]))
        return true;
      if (i >= k)
        seen.remove(nums[i - k]);
    }

    return false;
  }
}

Python

class Solution:
  def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
    seen = set()

    for i, num in enumerate(nums):
      if i > k:
        seen.remove(nums[i - k - 1])
      if num in seen:
        return True
      seen.add(num)

    return False