Contains Duplicate II

来源:互联网 发布:网络作家真实故事 编辑:程序博客网 时间:2024/06/10 00:44

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.

思路:用hashmap来用空间换时间,就是算每个出现的index跟前面的index距离是否超过k,如果 没有,return true,如果超过,覆盖index,继续往下走。

public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        if(nums == null || nums.length == 0 || k<=0) return false;        HashMap<Integer,Integer> hashmap = new HashMap<Integer, Integer>();        for(int i=0; i<nums.length; i++){            if(hashmap.containsKey(nums[i])){                if(i - hashmap.get(nums[i]) <=k){                    return true;                }else{                    hashmap.put(nums[i],i);                }            } else {                hashmap.put(nums[i],i);            }        }        return false;    }}


0 0
原创粉丝点击