【阿里笔试】合法连续子段
作者:互联网
滑动窗口 + hash
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, int> mp;
int n, m;
long long ans = 0;
scanf("%d%d", &n, &m);
vector<int> nums(n);
for(int i = 0; i < n; ++i) scanf("%d", &nums[i]);
for(int i = 0; i < m - 1; ++i) mp[nums[i]]++;
int right = 0;
for(int i = m - 1; i < n; ++i) {
mp[nums[i]]++;
if(mp[nums[i]] == m) {
int left = right;
while(nums[right] != nums[i]) {
--mp[nums[right++]];
}
ans += (long long)(right - left + 1) * (n - i);
--mp[nums[right++]];
}
}
cout << ans << endl;
}
标签:right,nums,int,子段,笔试,long,++,阿里,mp 来源: https://blog.csdn.net/qq_37702890/article/details/122859371