美文网首页
219. Contains Duplicate II

219. Contains Duplicate II

作者: bin_guo | 来源:发表于2018-07-09 12:15 被阅读0次

    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.

    Example 1:

    Input: nums = [1,2,3,1], k = 3
    Output: true

    Example 2:

    Input: nums = [1,0,1,1], k = 1
    Output: true

    Example 3:

    Input: nums = [1,2,3,1,2,3], k = 2
    Output: false

    Solution:
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:219. Contains Duplicate II

          本文链接:https://www.haomeiwen.com/subject/trizuftx.html