Skip to content

Commit 50e6375

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 12.3 MB (3.26%)
1 parent 2c131f2 commit 50e6375

1 file changed

Lines changed: 10 additions & 22 deletions

File tree

  • LeetCode/2316-count-hills-and-valleys-in-an-array
Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,18 @@
11
class Solution {
22
public:
33
int countHillValley(vector<int>& nums) {
4-
int ans=0;
5-
int n=nums.size();
6-
int p1=nums[0], p2=0, p3=0, idx=0;
7-
for (int i=0; i<n; i++) {
8-
if (nums[i] != p1 && !p2) p2 = nums[i];
9-
else if (nums[i] != p2 && p2 && !p3) p3 = nums[i];
10-
11-
if (p1 && p2 && p3) break;
12-
idx++;
4+
vector<int> vals;
5+
for (int i : nums) {
6+
if (vals.empty() || i != vals[vals.size()-1]) vals.push_back(i);
137
}
14-
if (!p3) return ans;
15-
16-
ans += (p1<p2 && p3<p2) || (p1>p2 && p3>p2);
17-
for (int i=idx+1; i<n; i++) {
18-
if (nums[i] != p3) {
19-
p1 = p2;
20-
p2 = p3;
21-
p3 = nums[i];
22-
23-
if ((p1<p2 && p3<p2) || (p1>p2 && p3>p2)) {
24-
ans++;
25-
}
26-
}
8+
9+
int ans = 0;
10+
int n = vals.size();
11+
for (int i=1; i<n-1; i++) {
12+
if (vals[i] >= vals[i-1] && vals[i] >= vals[i+1]) ans++;
13+
if (vals[i] <= vals[i-1] && vals[i] <= vals[i+1]) ans++;
2714
}
15+
2816
return ans;
2917
}
3018
};

0 commit comments

Comments
 (0)