LeetCode题解:Contains Duplicate II

来源:互联网 发布:淘宝麻辣烫底料 编辑:程序博客网 时间:2024/05/29 14:52

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.

题意:给定数组和整数k,找出数组内相同元素,且两个元素距离小于等于k

解决思路:和前一个思路一样,只不过多加一个判断

代码:

public boolean containsNearbyDuplicate(int[] nums, int k) {        Set<Integer> set = new HashSet<Integer>();        int i = 0, j = 0;        for (; j < nums.length; j++) {            if (j - i > k) {                set.remove(nums[i]);                i++;            }            if (set.contains(nums[j])) return true;            set.add(nums[j]);        }        return false;    }
0 0
原创粉丝点击