题意
题目链接
统计峰和谷
- 峰 nums[x-1] < nums[x] = nums[xn] > nums[x…n + 1]
- 股 nums[x-1] > nums[x] = nums[xn] < nums[x…n + 1]
思路
直接统计即可
代码
class Solution {
public:
int countHillValley(vector<int>& nums) {
int ans = 0;
int end = nums.size() - 1;
int index = 1;
while (index < end)
{
int l = index - 1;
int r = index + 1;
if (nums[l] < nums[index])
{
while (r < end && nums[index] == nums[r])
r++;
if (nums[index] > nums[r])
ans ++;
}
else if (nums[l] > nums[index])
{
while (r < end && nums[index] == nums[r])
r++;
if (nums[index] < nums[r])
ans ++;
}
index = r;
}
return ans;
}
};