845. Longest Mountain in Array
Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < … B[i-1] < B[i] > B[i+1] > … > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
- 0 <= A.length <= 10000
- 0 <= A[i] <= 10000
Follow up:
- Can you solve it using only one pass?
- Can you solve it in O(1) space?
Approach
- 给你一数组,问你数组中‘mountian’最长是多少,‘mountain’的定义是这一段数组中有一个最大值,以最大值为分界线左边是递增,右边是递减,当中不允许相等的元素,而且长度不小于3。这道题我的想法比较奇特,用到比较多的if-else ,首先做为mountian需要有一个上坡,我一开是我先要找到上坡,记录长度从一开始,如果当中有元素相等,那么重新记录长度从一开始,直至遇到下坡,当到达下坡的时候我就开始不断更新我的maxn(mountian的长度最大值),直至遇到上坡,我又重一开始记录长度,如果当中有元素相等,那么长度归为一,而且等待上坡再开始记录长度,时间复杂度为O(n),空间复杂度为O(1)。12ms
Code
class Solution {
public:
int longestMountain(vector<int>& A) {
if (A.size() < 3)return 0;
bool up = true;
int maxn = 0, cnt = 1;
for (int i = 0; i < A.size()-1; i++) {
if (up) {
if (A[i] < A[i + 1]) {
cnt++;
}
else if(A[i]==A[i+1]){
cnt = 1;
}
else if(cnt>1&&A[i]>A[i+1]){
cnt++;
maxn = max(cnt, maxn);
up = false;
}
}
else {
if (A[i] > A[i + 1]&&cnt>1) {
cnt++;
maxn = max(cnt, maxn);
}
else if(A[i]==A[i+1]) {
cnt = 1;
}
else if(A[i]<A[i+1]){
cnt = 1;
cnt++;
up = true;
}
}
}
return maxn;
}
};