Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork739
Description
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
iwith0 < i < A.length - 1such that:
Example 1:
Input: [2,1]Output: falseExample 2:
Input: [3,5,5]Output: falseExample 3:
Input: [0,3,2,1]Output: trueNote:
0 <= A.length <= 100000 <= 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://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
