leetCode-Contains Duplicate II

Posted kevincong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode-Contains Duplicate II相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

leetCode-Contains Duplicate II

LeetCode-Container With Most Water

leetcode-Container With Most Water-11

GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 错误

 Failed to destroy end point associated with ProtocolHandler["ajp-nio-8009"] Duplica

PHP返回error500 [重复]