LeetCode 3034. Number of Subarrays That Match a Pattern I
原题链接
中等
作者:
_YH_YH_
,
2024-02-20 05:14:42
,
所有人可见
,
阅读 35
class Solution {
public:
int countMatchingSubarrays(vector<int>& nums, vector<int>& p) {
int n = nums.size(), m = p.size();
vector<int> d;
for (int i = 0; i < n - 1; i++) {
int x = nums[i + 1] - nums[i];
if (x > 0) d.push_back(1);
else if (x < 0) d.push_back(-1);
else d.push_back(0);
}
int cnt = 0;
for (int i = 0; i < n - m; i++) {
bool flag = true;
for (int j = 0; j < m; j++) {
if (d[i + j] != p[j]) {
flag = false;
break;
}
}
if (flag) {
cnt++;
}
}
return cnt;
}
};