219. Contains Duplicate II (HashTable)

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.

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<Integer>();
        for(int i = 0; i < nums.length; i++){
            if(set.contains(nums[i])){
                return true;
            }
            set.add(nums[i]);
            if(set.size()>k){
                set.remove(nums[i-k]);
            }
        
        }
        return false;
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 好久都没有动笔写过字,而这儿也快没了我的痕迹。所有关于梦想的小心思淡漠了,差点就这样混天度日的过去,现在行动起来无...
    亦戈梦阅读 284评论 0 1
  • 才子佳人自多情 歌咏诗文若繁星 哪有少男不爱色 哪个少女不怀春
    一叶茶阅读 322评论 0 1
  • 见你蔫在太阳下 他跑了好远好远捧来这口水 你抖抖身体活了过来 花瓣上 滑落下了最后一滴水珠 你模样可真好看 阳光下...
    可爱的怪阿姨阅读 179评论 0 2
  • 一 周日的晚上我们把女儿从父母那里接回家,才刚到家,母亲就追来质问电话: “宝宝晚上钙片吃了吗?” “没有,忘记了...
    守妈育儿札记阅读 353评论 0 1