File tree Expand file tree Collapse file tree
LeetCode/2316-count-hills-and-valleys-in-an-array Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11class Solution {
22public:
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};
You can’t perform that action at this time.
0 commit comments