文章目录
- 1. 题目来源
- 2. 题目解析
1. 题目来源
链接:2808. 使循环数组所有元素相等的最少秒数
2. 题目解析
一道比较简单的思维题吧,将一维数组首尾连接变成环,会发现相同元素中间的距离 / 2,就是需要感染的秒数。包括首尾连接的字符也要算下距离。
易错点:
- 主要是代码实现上,一开始写的版本太复杂,导致边界问题没考虑,出WA。
- 注意 上取整还是下取整的问题,简单举个例子就知道了。
- 首尾相同元素距离的问题,分成 0----首, 尾—n 两段,加起来求和即可,常用技巧
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)
class Solution {
public:int minimumSeconds(vector<int>& nums) {unordered_map<int, vector<int>> mp;int n = nums.size(), res = n;for (int i = 0; i < n; ++i) {mp[nums[i]].push_back(i);}for (auto& pos : mp) {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]);}res = min(res, mx / 2);}return res;}
};