-
Notifications
You must be signed in to change notification settings - Fork 693
/
Solution.java
79 lines (56 loc) · 2.04 KB
/
Solution.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//Problem: https://www.hackerrank.com/challenges/minimum-distances
//Java 8
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int A[] = new int[n];
for(int A_i=0; A_i < n; A_i++){
A[A_i] = in.nextInt();
}
/*
First Iteration
[7 1 3 4 1 7]
Set _______ runnningMin
7 : 5 / 3
1 : 1
3 : 3
4 : 2
-store the shortest so far for a pair
-store the starting point of possible future pairs
-update start point to the end point if
TC: O(n^2) SC: O(n)
Second Iteration
instead of incrementing our distance each time we move our starting
point to the right, we are going to just store the index of each value
This is now TC: O(n) SC: O(n)
*/
HashMap<Integer,Integer> distances = new HashMap<>();
int minDistance = -1;
for(int i = 0; i < n; i++)
{
if(distances.containsKey(A[i]))
{
//Calculate distance between like numbers
int distance = Math.abs(distances.get(A[i]) - i);
if( distance < minDistance || minDistance == -1)
{
minDistance = distance;
}
//Set start point to the old end point
distances.put(A[i], i);
}
else
{
//Add a new starting point
distances.put(A[i], i);
}
}
System.out.println(minDistance);
}
}