941. Valid Mountain Array

problem

solution

只會有一個peak

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool validMountainArray(vector<int>& arr) {
int n =arr.size();
if(n<3) return false;
int l =0 , r = n-1;
while(l<r && arr[l] < arr[l+1]) l++;
while(l<r && arr[r-1] > arr[r]) r--;
return (l!=0) && (r!=n-1) &&(l==r);
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)