leetcode-219-easy

Contains Duplicate II
思路一: for 循环遍历,结果超时

public boolean containsNearbyDuplicate(int[] nums, int k) {
    int left = -1;

    for (int i = 0; i < nums.length; i++) {
        left = i;
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[left] == nums[j]) {
                if (Math.abs(left - j) <= k) return true;
                else left = j;
            }
        }
    }

    return false;
}

思路二: 用 map 记录数组下标信息,遇到相等的数字取出下标对比

public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(nums[i])) {
            if (Math.abs(map.get(nums[i]) - i) <= k) return true;
            else map.put(nums[i], i);
        } else {
            map.put(nums[i], i);
        }
    }
    return false;
}
posted @ 2022-10-19 07:36  iyiluo  阅读(24)  评论(0)    收藏  举报