(219)-(Contains Duplicate II)-(判断数组中出现重复值的两个元素,位置差最多为k)-(HashSet及时删除元素)

(219)-(Contains Duplicate II)-(判断数组中出现重复值的两个元素,位置差最多为k)-(HashSet及时删除元素)

//Given an array of integers and an integer k,
//find out whether there 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

public class Solution 
{
   public boolean containsNearbyDuplicate(int[] nums, int k)
        {
            Set<Integer> my_set=new HashSet<Integer>();
            
            //数组为空,0元素,1元素都不会重复的
            if(nums==null||nums.length==0||nums.length==1)
            {
                return false;
            }
            //位置差最多为0,不合理
            if(k==0)
            {
                return false;
            }
            
            //最多为K,即小于K+1的都可以
            int cap=k+1;
            
            for(int i=0;i<nums.length;i++)
            {
                if(i<cap)
                {
                    //都可以的,不删元素
                }
                else
                {   
                    //超出,从set中进行删除之前的元素
                    //1 2 3 1 最多为2,删除第一个1
                    Integer curr = nums[i-cap];
                    my_set.remove(curr);
                }
                if(my_set.contains(nums[i]))
                {
                    return true;
                }
                else
                {
                    my_set.add(nums[i]);
                }
            } 
            return false;
        }
}

 

posted @ 2015-07-25 19:30  爱吃萝卜干  阅读(129)  评论(0编辑  收藏  举报