首页 > 其他分享 >leetcode-219-easy

leetcode-219-easy

时间:2022-10-19 07:45:10浏览次数:51  
标签:map nums int 219 ++ length easy leetcode left

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;
}

标签:map,nums,int,219,++,length,easy,leetcode,left
From: https://www.cnblogs.com/iyiluo/p/16804876.html

相关文章