Title: Contains Duplicate II Source: leetcode.com
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.
Java solution
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 |
/* https://leetcode.com/problems/contains-duplicate-ii/ */ import java.util.HashMap; public class ContainsDuplicateII { public static void main(String args[]) { } public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++) { if(!map.containsKey(nums[i])) { map.put(nums[i], i); } else { int index = map.get(nums[i]); if(i-index <= k) return true; else map.put(nums[i], i); } } return false; } } |