[LeetCode 219] Contains Duplicate II

来源:互联网 发布:苹果如何删除windows 编辑:程序博客网 时间:2024/05/16 05:01

Given an array of integers and an integer k, find out whether there are two distinct indicesi and j in the array such that nums[i] = nums[j] and the difference betweeni and j is at most k.

solution:

Use hashmap, key is the element value, value is the element index.

O(n)

public boolean containsNearbyDuplicate(int[] nums, int k) {        int len = nums.length;        if(len <= 1) return false;        Map<Integer, Integer> count = new HashMap<>();        for(int i = 0;i < len; i++) {            if(count.containsKey(nums[i])) {                if(Math.abs(count.get(nums[i]) - i) <= k) return true;            }            count.put(nums[i], i);        }        return false;    }




0 0