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

给定一个数组,和一个整数k,判断该数组中是否存在不同下标的 i 和 j 两个元素,使得 nums[i] = nums[j],且 i 和 j 的差不超过k。

 1     public boolean containsNearbyDuplicate(int[] nums, int k) {
 2         if (nums == null || nums.length == 0)
 3             return false;
 4         Map<Integer, List<Integer>> numberMap = new HashMap<>();
 5         for (int i = 0; i < nums.length; i++) {
 6             List<Integer> indexs = numberMap.getOrDefault(nums[i], new ArrayList<>());
 7             indexs.add(i);
 8             numberMap.put(nums[i], indexs);
 9         }
10         for (Map.Entry<Integer,List<Integer>> entry:numberMap.entrySet())
11         {
12             if (entry.getValue().size()>1)
13             {
14                 List<Integer> indexs = entry.getValue();
15                 for (int i=indexs.size()-1; i>0;i--)
16                 {
17                     if(indexs.get(i) - indexs.get(i-1) <= k)
18                         return true;
19                 }
20             }
21         }
22         return false;        
23     }

 

posted @ 2017-10-14 21:47  daniel456  阅读(154)  评论(0编辑  收藏  举报