ContainsDuplicate II

来源:互联网 发布:java类和对象的概念 编辑:程序博客网 时间:2024/05/18 10:17

问题描述:

检测数组中是否有重复元素,并且两元素的下标差值小于等于k。


解决:

这道题也是判断数组里是否存在两个相同的数,并且需要这两数的下标差值不能大于k。由于之前没有下标的要求,所有用set来辅助存储元素值就可以。但是有了下标差值的要求,我们需要使用map来存储元素值和对应的下标。每次遇到相同元素了需要判断下标差值是否满足要求,如果不满足要求,要及时对map进行更新,对于相同的值需要更新它的下标。


/* * 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. */import java.util.HashMap;import java.util.Map; public class ContainsDuplicateII {    public boolean containsNearbyDuplicate(int[] nums, int k) {        if(nums == null || nums.length < 2)                        return false;        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i=0; i<nums.length; i++) {                if(map.containsKey(nums[i])) {                        if(i-map.get(nums[i]) <= k) {                                return true;                        } else {             //更新nums[i]的下标                                map.remove(nums[i]);                                map.put(nums[i], i);                        }                } else {                map.put(nums[i], i);                }        }        return false;    }}