您的位置:首页 > 大数据 > 人工智能

LeetCode题解:Contains Duplicate II

2015-08-12 11:11 387 查看
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;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: