Consider an array of integers, . The distance between two indices, and , is denoted by .
Given , find the minimum such that and . In other words, find the minimum distance between any pair of equal elements in the array. If no such value exists, print .
Note: denotes the absolute value of .
Input Format
The first line contains an integer, , denoting the size of array .
The second line contains space-separated integers describing the respective elements in array .
The second line contains space-separated integers describing the respective elements in array .
Constraints
Output Format
Print a single integer denoting the minimum in ; if no such value exists, print .
Sample Input
6
7 1 3 4 1 7
Sample Output
3
Explanation
Here, we have two options:
Here, we have two options:
- and are both , so .
- and are both , so .
The answer is .
Solution:
- #include <bits/stdc++.h>
- using namespace std;
- int last_index[100001];
- int main(){
- int n, x;
- scanf("%d", &n);
- int distance = INT_MAX;
- for(int i = 1; i <= n; i++){
- scanf("%d", &x);
- if(last_index[x])distance = min(distance, i-last_index[x]);
- last_index[x] = i;
- }
- if(distance == INT_MAX)distance = -1;
- printf("%d\n", distance);
- return 0;
- }
No comments:
Post a Comment