题目描述
给定一个数组,请你找出数组中相同元素之间的最远距离。若数组中不存在相同元素,则输出 null。
输入描述
输入一个数组,数组长度不超过 10000。格式请见用例。
输出描述
输出数组中相同元素的最远距离。
用例
输入
[3, 2, 3, 2, 3, 2, 3, 2]
Copy
输出
6
Copy
说明
索引0的元素和索引6的元素相同,距离 6。
索引1的元素和索引7的元素相同,距离 6。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int M = 1e6 + 10;
vector<int> v;
struct Node
{
int l=1e6;
int r=-1;
};
void solve() {
string str;
getline(cin, str);
str = str.substr(1, str.size() - 2);
size_t pos = 0;
while ((pos = str.find(',')) != string::npos) {
v.push_back(stoi(str.substr(0, pos)));
str.erase(0, pos + 1);
}
v.push_back(stoi(str));
// for(auto x:v)cout<<x<<" ";
int res=0;
map<int,Node>mp;
for(int i=0;i<v.size();i++){
if(mp[v[i]].l>i)mp[v[i]].l=i;
if(mp[v[i]].r<i)mp[v[i]].r=i;
res=max(mp[v[i]].r-mp[v[i]].l,res);
}
if(res==0)cout<<"null"<<endl;
else
cout<<res<<endl;
}
signed main() {
solve();
return 0;
}