leetcode 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.

这道题目的意思是:输入一个整数数组和一个整数k,若是数组中存在相等的两个数,并且他们的位置差不超过k,那么返回true,不然返回false数组

思路

  • 这道题比较容易想到的想法就是用hashmap来存储不一样值的元素的值(key)和位置信息(value)。而后在每次遍历的时候进行比较。
  • 但上面这个想法并非最简单的,若是咱们对任何索引大于k的元素进行遍历的时候,同时删除hashset中和当前元素的位置差已经超过k的对应元素。这样就能够减小后序查找的时间。
  • 这样只要新遍历到的元素的值已经存在于hashset之中,咱们就能够判定,这两个元素的位置差必定是小于k的了。

解法

int length = nums.length;
        if(length<=1) return false;
        Set<Integer> count = new HashSet<Integer>();
        
        for(int i=0;i<length;i++){
            if(i > k){
                count.remove(nums[i-k-1]);
            }
            if(!count.add(nums[i])){
                return true;
            }
        }
        return false;
相关文章
相关标签/搜索