Contains Duplicate II 是否包含重复

来源:互联网 发布:网络安全教育开题报告 编辑:程序博客网 时间:2024/06/11 17:54

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.

跟前一题的差别是,它限制了重复的元素的index差在k范围内。

一个思路就是,在判断重复的set里面只放index 差在k范围内的元素

运行时间:


代码:

public class ContainsDuplicateII {    public boolean containsNearbyDuplicate(int[] nums, int k) {        Set<Integer> set = new HashSet<>();        for (int i = 0; i < nums.length; i++) {            // remove the element whose index are out of k             if (i > k) {                set.remove(nums[i - k - 1]);            }            if (!set.add(nums[i])) {                return true;            }        }        return false;    }}


1 0
原创粉丝点击