算法系列——存在重复元素(Contains Duplicate II)

100 阅读1分钟

题目描述

题目链接:leetcode-cn.com/problems/co…
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.

实现思路

还是哈希表思路,key 为 值,value为索引。时间复杂度为O(n)
空间复杂度为O(n)

程序实现

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