219. Contains Duplicate II - LeetCode

Question

219. Contains Duplicate II

Solution

题目大意:数组中两个相同元素的坐标之差小于给定的k,返回true,否则返回false

思路:用一个map记录每个数的坐标,如果数相同,如果坐标差小于k则返回true否则覆盖,继续循环

Java实现:

public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int tmp = nums[i];
        if (map.get(tmp) != null) {
            // System.out.println(i + "---" + map.get(tmp));
            if (i - map.get(tmp) <= k) return true;
        } 
        map.put(tmp, i);
    }
    return false;
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9337542.html