941. Valid Mountain Array(python+cpp)
阿新 • • 發佈:2018-11-21
題目:
Given an array
A
of integers, return true if and only if it is a valid mountain array.
Recall thatA
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: 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
解釋:
注意,要求只有一個山峰,用雙指標,分別從兩邊往中間爬,判斷最終兩個指標是否指向同一個值而且在範圍內。
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+1<len_A and A[i+1]>A[i]:
i+=1
while j-1>=0 and A[j-1]>A[j]:
j-=1
return 0<i==j<len_A-1
c++程式碼:
class Solution {
public:
bool validMountainArray(vector<int>& A) {
int i=0,j=A.size()-1,len_A=A.size();
while(i+1<len_A && A[i+1]>A[i])
i++;
while(j-1>=0 && A[j-1]>A[j])
j--;
return i==j && i>0 && j<len_A-1;
}
};
總結:
需要注意的就是,題目要求只有一個山峰。