题目地址https://leetcode.cn/problems/minimum-seconds-to-equalize-a-circular-array/description/
代码解析
class Solution {
public:
int minimumSeconds(vector<int>& nums) {
unordered_map<int, vector<int>> mp; //二维链表
//关于为什么res(ult)初始化为n我的理解是:
//在nums中相同元素相距最远的情况就是在nums的两端有相同的元素,
//因此当初始化大于n时无意义,当初始化小于n时可能考虑不全面。
int n = nums.size(), res = n;
for(int i = 0; i < n; i++){
//这里假如nums为:nums = [2,1,3,3,2,2,2,3,3,2,3,2,3,2,3,2,3,2]
//mp = {[3] = {2, 3, 7, 8, 10, 12, 14, 16}, [1] = {1}, [2] = {0, 4, 5, 6, 9, 11, 13, 15, 17}}
//其中[]内为元素,{}内为下标的顺序集合(因为我们是从i=0开始依次pushback的)
mp[nums[i]].push_back(i);
}
for(auto& pos: mp){
// mx初始化的这个值为,将循环数组首尾连在一起之后,首尾元素相距的距离。
// 即2,3,3,3,3,3,3,3,2 中首尾两个3的距离是3。
int mx = pos.second[0] + n - pos.second.back();
//分别计算相邻两个位置相同元素之间的最大距离。
//首尾元素相距的距离并不一定时最大,因为是循环数组,首尾相接的。
for(int i = 1; i < pos.second.size(); ++i){
mx = max(mx, pos.second[i] - pos.second[i - 1]);
}
// 这里除2是因为两个元素相互“靠近”的最大速度就是2,右面的向左走一步,左面的向右走一步。
res = min(res, mx / 2);
}
return res;
}
};
如有错误敬请指正