219. Contains Duplicate II

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 absolute difference between i and j is at most k.

Solution1:hashset

Time Complexity: O(N) Space Complexity: O(k)

Solution1 Code:

class Solution {
    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
  • 明天我们就要去游泳了,妈妈带了很多东西:“泳衣、游泳圈、防晒霜、毛巾等等。 ...
    蓝色之冥阅读 1,599评论 2 1
  • 家里的《我们仨》不知被谁借走了,没有下落。之前没有去读,待想读时又迫切想读,急忙下单,就等书到了开读。我不是在大家...
    铃兰小语阅读 1,313评论 0 1
  • 有了手机要电脑,有了电脑用平板,有了平板要相机,外加一个kindle阅读器 我的生活几乎是被点罪产品所包围,还有一...
    迷惘之乡阅读 1,274评论 0 0