Created
October 9, 2016 09:12
-
-
Save tmosest/4f28a8b6d46e708ab35d55ce5b045e18 to your computer and use it in GitHub Desktop.
Hackerrank: Minimum Distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
import java.text.*; | |
import java.math.*; | |
import java.util.regex.*; | |
import java.util.Arrays; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
Map<Integer, Integer> hm = new HashMap<>(); | |
int minDist= Integer.MAX_VALUE; | |
int n = in.nextInt(); | |
int[] arr = new int[n]; | |
for(int i=0; i < n; i++){ | |
arr[i] = in.nextInt(); | |
if(hm.containsKey(arr[i])) { | |
int x=hm.get(arr[i]); | |
int dist = i - x; | |
if(dist < minDist) minDist = dist; | |
} | |
else hm.put(arr[i],i); | |
} | |
if(minDist == Integer.MAX_VALUE) minDist=-1; | |
System.out.println(minDist); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment