LeetCode-Contains Duplicate II

Posted LiBlog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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 difference between i and j is at most k.

Solution:

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums.length<2) return false;
        
        HashSet<Integer> numSet = new HashSet<Integer>();
        for (int i=0;i<nums.length;i++){
            if (numSet.contains(nums[i])){
                return true;
            }
            
            //add nums[i] into set
            numSet.add(nums[i]);
            
            // if full, then remove the left most one.
            if (numSet.size()>k)
                numSet.remove(nums[i-k]);
            
        }
        
        return false;
    }
}

 

以上是关于LeetCode-Contains Duplicate II的主要内容,如果未能解决你的问题,请参考以下文章

leetCode-Contains Duplicate II

GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 错误

 Failed to destroy end point associated with ProtocolHandler["ajp-nio-8009"] Duplica

PHP返回error500 [重复]

Ubuntu apache vhostu别名安装程序

MySQL INSERT ON DUPLICATE KEY UPDATE