Contains Duplicate II Leetcode

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.

 
这道题思路很简单,只是需要注意一下,任何情况都要把当前的nums[i],i放进map,因为每次都是比较最近的index。
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        Map<Integer, Integer> hm = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hm.containsKey(nums[i])) {
                if (i - hm.get(nums[i]) <= k) {
                    return true;
                }
            }
            hm.put(nums[i], i);
        }
        return false;
    }
}

还可以用hashset做,而且好像比hashmap更快啊。

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        Set<Integer> hs = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                hs.remove(nums[i - k - 1]);
            }
            if (!hs.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}

 

附上C++写法:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_set<int> s;
        
        for (int i = 0; i < nums.size(); i++) {
            if (i > k) {
                s.erase(nums[i - k - 1]);
            }
            if (s.find(nums[i]) != s.end()) {
                return true;
            }
            s.insert(nums[i]);
        }
        return false;
    }
};

 

posted @ 2017-06-08 03:46  璨璨要好好学习  阅读(115)  评论(0编辑  收藏  举报