1. 程式人生 > >219. Contains Duplicate II

219. Contains Duplicate II

fault bsp 元素 不同 ray log boolean 判斷 absolut

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 }

219. Contains Duplicate II