219. Contains Duplicate II

如果采用二重遍历会超时,所以需要用一些数据结构优化:

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]);   //只保留k+i - i + 1个元素
            if(!set.add(nums[i]))    //在此范围内加入重复的元素add会返回false
                return true;
        }
        return false;
    }
}
  • Set集合里多个对象之间没有明显的顺序
  • Set集合不允许重复元素,HashSet集合判断两个元素相等的标准是两个对象通过equals方法比较相等,并且两个对象的hashCode()方法返回值也相等。

ASet represents a generic "set of values". A TreeSet is a set where the elements are sorted (and thus ordered), a HashSet is a set where the elements are not sorted or ordered. A HashSet is typically a lot faster than a TreeSet.
A TreeSet is typically implemented as ared-black tree, whereas a HashSet uses Object.hashCode() to create an index in an array. Access time for a red-black tree is O(log(n)) whereas access time for a HashSet ranges from constant-time to the worst case (every item has the same hashCode) where you can have a linear search time O(n).

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • #轻写作#第2篇 谈到意志力,我们首先会联想到的,可能是去做一件自己并不非常乐意去做但又不得不做的事情,又或者是去...
    生命本来就是没有名字阅读 3,465评论 0 0
  • 我总是喜欢自言自语的唱歌, 比如唱一些高山 河流 鸟 和随风飘落的树叶。 我的祖先开天辟地, 我倾听一条河流的声音...
    道临阅读 3,321评论 0 0
  • 一脚踏进这样的工作环境,走进所谓的员工食堂,走进所谓的员工宿舍,眼泪一次又一次的憋在眼眶里打转,我高傲的内心一次又...
    巴啦啦小排骨阅读 1,531评论 0 0

友情链接更多精彩内容