Leetcode - Contains Duplicate II

来源:互联网 发布:dota2公开比赛数据 编辑:程序博客网 时间:2024/05/29 07:32

Question

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 difference between i and j is at most k.


Java Code

public boolean containsNearbyDuplicate(int[] nums, int k) {    int len = nums.length;    //使用HashMap容器存储已经遍历过的数组元素及其索引    HashMap<Integer, Integer> map = new  HashMap<>(2*len);    int num;    Integer temp;    for(int i = 0 ; i < len;  ++i) {        num = nums[i];        //如果map中不存在此元素或其索引与当前元素的索引之差超过k,则存入/更新该元素及其索引        if((temp = map.get(num)) == null || temp < i - k)            map.put(num, i);        else//如果map中已经存在此元素,且其索引与当前元素的索引之差不超过k,则满足条件            return true;    }    return false;}
0 0
原创粉丝点击