本文共 1133 字,大约阅读时间需要 3 分钟。
题目:
Given an array
Recall thatA
of integers, return true if and only if it is a valid mountain array.A
is a mountain array if and only if:A.length >= 3
There exists somei
with0 < i < A.length - 1
such that:A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[B.length - 1]
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 <= 10000
0 <= A[i] <= 10000
解释:
注意,要求只有一个山峰,用双指针,分别从两边往中间爬,判断最终两个指针是否指向同一个值而且在范围内。 python代码:class Solution: def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if len(A)<3: return False i,j,len_A=0,len(A)-1,len(A) while i+1A[i]: i+=1 while j-1>=0 and A[j-1]>A[j]: j-=1 return 0
c++代码:
class Solution { public: bool validMountainArray(vector & A) { int i=0,j=A.size()-1,len_A=A.size(); while(i+1A[i]) i++; while(j-1>=0 && A[j-1]>A[j]) j--; return i==j && i>0 && j
总结:
需要注意的就是,题目要求只有一个山峰。转载地址:http://fwmcn.baihongyu.com/