219. Contains Duplicate II

My Submissions

Total Accepted: 88264
Total Submissions: 281930
Difficulty: Easy
Contributors: Admin

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

Hide Company Tags
Palantir Airbnb
Hide Tags
Array Hash Table
Hide Similar Problems
(E) Contains Duplicate (M) Contains Duplicate III

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.

Reference - simple-java-solution

    // https://discuss.leetcode.com/topic/15305/simple-java-solution/6
    public boolean containsNearbyDuplicate(int[] nums, int k) {
      Set<Integer> set = new HashSet<Integer>();
      for (int i = 0; i < nums.length; i++) {
          if (i > k) set.remove(nums[i - k - 1]);
          if (!set.add(nums[i])) return true;
      }
      return false;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,487评论 0 23
  • 远方的你 陪在我身边一起看那海蓝蓝 可是我 却分不清你离我是近还是远 但,我依然相信 缘分会让你我今生彼此牵绊
    木薯羹阅读 803评论 0 0
  • 一、URI与Uri 大家可能经常会看到在开发时,怎么有的时候是URI,有的时候是Uri,这是怎么回事? 名称如此相...
    Ten_Minutes阅读 12,520评论 4 8
  • 今日是王座中蚂蚁列队最有力的 一阵风吹雨袭,一阵阳光清明 人民争做落叶的扫除工 余我凭窗眺望荷池 无记事的历史,也...
    诗人金子阅读 1,670评论 0 2