217, 219,220. Contains Duplicate I, II, III

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        // if(nums==null||nums.length==0) return false;
        HashSet<Integer> sets = new HashSet<>();
        for(int i=0; i<nums.length; i++){
            if(!sets.contains(nums[i]))
                sets.add(nums[i]);
            else return true;
        }
        return false;
    }
}


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.

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(nums.length);
        for(int i=0; i<nums.length; i++){
            if(!map.containsKey(nums[i]))
                map.put(nums[i],i);
            else {
                if(i-map.get(nums[i])<=k) return true;
                else map.put(nums[i],i);
            }
        }
        return false;
    }
}

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(t<0||k<=0) return false;
        k = Math.min(k,nums.length);
        TreeSet<Long> kwindow = new TreeSet<Long>();
        for(int i=0; i<nums.length; i++){
            SortedSet<Long> subset = kwindow.subSet((long)nums[i]-Math.abs(t),(long)nums[i]+Math.abs(t)+1);
            if(subset!=null && subset.size()>0) return true;
<span style="white-space:pre">	</span>    //if first add <span style="font-family: Arial, Helvetica, sans-serif;">nums[i]</span><span style="font-family: Arial, Helvetica, sans-serif;">, then remove </span><span style="font-family: Arial, Helvetica, sans-serif;">nums[i-k]</span><span style="font-family: Arial, Helvetica, sans-serif;">, in case of nums[i]==nums[i-k], it will remove both; so we need to first remove nums[i-k] then add nums[i]</span><span style="font-family: Arial, Helvetica, sans-serif;">
</span>            if(i>=k){
                kwindow.remove((long)nums[i-k]);
            }
            kwindow.add((long)nums[i]);
        }
        return false;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章