|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importjava.util.HashMap; |
| 4 | +importjava.util.Map; |
| 5 | + |
| 6 | +/**219. Contains Duplicate II QuestionEditorial Solution My Submissions |
| 7 | +Total Accepted: 69920 |
| 8 | +Total Submissions: 228733 |
| 9 | +Difficulty: Easy |
| 10 | +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.*/ |
| 11 | +publicclassContainsDuplicateII { |
| 12 | +//pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array |
| 13 | +//we can keep updating the value as we move forward, since if the current index minus the last index cannot be smaller than k, then |
| 14 | +//the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers! |
| 15 | +publicbooleancontainsNearbyDuplicate(int[]nums,intk) { |
| 16 | +Map<Integer,Integer>map =newHashMap(); |
| 17 | +for(inti =0;i <nums.length;i++){ |
| 18 | +if(map.containsKey(nums[i])) { |
| 19 | +if(i -map.get(nums[i]) <=k)returntrue; |
| 20 | +elsemap.put(nums[i],i); |
| 21 | + } |
| 22 | +elsemap.put(nums[i],i); |
| 23 | + } |
| 24 | +returnfalse; |
| 25 | + } |
| 26 | +} |