力扣2831.找出最长等值子数组
思路:用二维数组存每个数字的出现下标
- 遍历所有数字求结果
- 当前子数组大小:pos[i] - pos[j] + 1;
- 当前相同数个数:i - j + 1;
- 需要删去的数的个数:pos[i] - pos[j] - i + j;
class Solution { public: int longestEqualSubarray(vector<int>& nums, int k) { int n = nums.size(); vector<vector<int>> pos_list(n+1); for(int i=0;i<n;i++) { pos_list[nums[i]].emplace_back(i); } int res =0; for(auto pos:pos_list) { for(int i=0,j=0;i<pos.size();i++) { while(pos[i] - pos[j] - i + j > k) j ++; res = max(res,i-j+1); } } return res; } };