GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/java/219_Contains_Duplicate_II.java at master · allenphilip93/leetcode Expand file tree/ Copy path219_Contains_Duplicate_II.javaMore file actions 44 lines (36 loc) · 1.23 KB / Copy path219_Contains_Duplicate_II.javaFile metadata and controls44 lines (36 loc) · 1.23 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 import java.util.*; class Solution { /* * I have to save indice for each index. * So I use the HashMap<Integer, List<Integer>> */ public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, List<Integer>> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { if(!map.containsKey(nums[i])) { map.put(nums[i], new ArrayList<>()); } map.get(nums[i]).add(i); } // use Iterator to find appropriate two indice. // Each list guarantee ascending. // So list.get(i) and list.get(i + 1) is minimum. Iterator<Integer> keys = map.keySet().iterator(); boolean answer = false; while(keys.hasNext()) { int key = keys.next(); List<Integer> list = map.get(key); if(list.size() < 2) continue; for(int i = 1; i < list.size(); i++) { int a = list.get(i - 1); int b = list.get(i); if(b - a <= k) { answer = true; break; } } if(answer) break; } return answer; } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |