Contains Duplicate II

描述

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, key为整数,value为下标,将数组中的元素不断添加进这个HashMap, 碰到重复时,计算二者的下标距离,如果距离小于或等于k,则返回true, 如果直到数组扫描完,距离都大于k,则返回false。

代码

  1. // Contains Duplicate II
  2. // Time Complexity: O(n), Space Complexity: O(n)
  3. public class Solution {
  4. public boolean containsNearbyDuplicate(int[] nums, int k) {
  5. final Map<Integer, Integer> map = new HashMap<>();
  6. int min = Integer.MAX_VALUE;
  7. for(int i = 0; i < nums.length; i++){
  8. if(map.containsKey(nums[i])){
  9. final int preIndex = map.get(nums[i]);
  10. final int gap = i - preIndex;
  11. min = Math.min(min, gap);
  12. }
  13. map.put(nums[i], i);
  14. }
  15. return min <= k;
  16. }
  17. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/contains-duplicate-ii.html