1. 程式人生 > >leetCode-Contains Duplicate II

leetCode-Contains Duplicate II

dup urn map [] spa absolute ray 通過 abs

Decsription:
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.

My Solution:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int
k) { Map<Integer,List> indexMap = new<Integer,List> HashMap(); int len = nums.length; for(int i = 0;i < len;i++){ List<Integer> list; if(indexMap.get(nums[i]) == null){ list = new ArrayList<Integer>(); list.add(i); indexMap.put(nums[i],list); }
else{ list = (ArrayList<Integer>)indexMap.get(nums[i]); list.add(i); } if(list.size() >= 2){ if(list.get(list.size() - 1) - list.get(list.size() - 2) <= k){ return true; } } }
return false; } }

Better Solution:

//set相當於緩存k+1個不相等的元素,一旦個數超過k+1個,那麽每次都會清除掉"隊首"元素(set無序,形象化理解是這樣,其實是通過nums[i - k + 1]實現的)。因此,如果一個元素加入set,
!set.add()返回true,則說明有兩個元素相等且diff<=k;
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                set.remove(nums[i - k - 1]);
            }
            set.add(),如果set包含nums[i],那麽返回false,如果不包含,返回true
            if (!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}

Best Solution:

class Solution {
//通過map保存元素下標
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(k > 3000) return false;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && (i - map.get(nums[i]) <= k)) {
                return true;
            } else {
                map.put(nums[i], i);
            }
        }
        return false;
    }
}

leetCode-Contains Duplicate II