Given an array `A` of integers, return `true` if and only if it is a *valid mountain array*.
Recall that A is a mountain array if and only if:
A.length >= 3
- There exists some
i
with0 < i < A.length - 1
such that:A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]
Example 1:
Input: [2,1]
Output: false
Example 2:
Input: [3,5,5]
Output: false
Example 3:
Input: [0,3,2,1]
Output: true
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
這道題定義了一種山形數組,長度大於等於3,並且存在一個峰值,左右兩邊的數字都必須嚴格遞減,不允許有相等的值存在。就是說從開頭遍歷,一定是嚴格遞增的,直到到達峰值,然后嚴格遞減到末尾,那么可以從開頭進行 while 循環,若當前數字小於右邊的數字,則i自增1,為了避免溢出,i只能遍歷到倒數第二個數字,這樣當循環結束的時候,i指向的數字是大於等於右邊的數字,是潛在的峰值,當然這里是不能相等的,但此時不需要判斷。同樣的操作反向來一遍,j從最后一個數字遍歷到第二個數字,若當前數字小於其左邊的數字時,則j自減1,這樣循環結束后,j指向的數字是大於等於左邊的數字的,也是潛在的峰值。接下來就要比較這兩個峰值是否指向同一個數字,同時i指向的數字不能是第一個,j指向的數字不能是最后一個數字,因為必須要有上坡和下坡的存在,參見代碼如下:
class Solution {
public:
bool validMountainArray(vector<int>& A) {
int n = A.size(), i = 0, j = n - 1;
while (i < n - 1 && A[i] < A[i + 1]) ++i;
while (j > 0 && A[j - 1] > A[j]) --j;
return i > 0 && j < n - 1 && i == j;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/941
參考資料:
https://leetcode.com/problems/valid-mountain-array/
https://leetcode.com/problems/valid-mountain-array/discuss/194941/C%2B%2B-Track-Peak
https://leetcode.com/problems/valid-mountain-array/discuss/194900/C%2B%2BJavaPython-Climb-Mountain
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)