Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Example 1:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 104
这题的通过率只有33%,但是题目初看是不难的,应该有不少边界条件很容易忽略。
这个主要是找一个数组是否有单调递增+单调递减的组成。首先不能有相等的,这样肯定不符合条件,并且初始肯定要单调递增,初始单调递减的肯定也不对,所以我们按两个部分分别判断递增和递减就可以了。
class ValidMountainArray : public Solution {
public:
void Execute() {
}
bool validMountainArray(vector<int>& arr) {
if (arr.size() < 3) {
return false;
}
std::size_t i = 1;
bool top = false;
for (; i < arr.size(); i++) {
if (arr[i] == arr[i - 1]) {
return false;
}
if (arr[i] < arr[i - 1]) {
top = true;
if (i == 1) {
return false;
}
break;
}
}
if (!top) {
return false;
}
for (; i < arr.size(); i++) {
if (arr[i - 1] <= arr[i]) {
return false;
}
}
return true;
}
};