0941.有效的山脉数组 添加Java版本

This commit is contained in:
posper
2021-07-28 14:47:26 +08:00
parent 8b15ec147c
commit 3be442c833

View File

@ -18,7 +18,7 @@ https://leetcode-cn.com/problems/valid-mountain-array/
C++代码如下: C++代码如下:
``` ```c++
class Solution { class Solution {
public: public:
bool validMountainArray(vector<int>& A) { bool validMountainArray(vector<int>& A) {
@ -38,6 +38,33 @@ public:
} }
}; };
``` ```
Java 版本如下:
```java
class Solution {
public boolean validMountainArray(int[] arr) {
if (arr.length < 3) { // 此时,一定不是有效的山脉数组
return false;
}
// 双指针
int left = 0;
int right = arr.length - 1;
// 注意防止指针越界
while (left + 1 < arr.length && arr[left] < arr[left + 1]) {
left++;
}
// 注意防止指针越界
while (right > 0 && arr[right] < arr[right - 1]) {
right--;
}
// 如果left或者right都在起始位置说明不是山峰
if (left == right && left != 0 && right != arr.length - 1) {
return true;
}
return false;
}
}
```
如果想系统学一学双指针的话, 可以看一下这篇[双指针法:总结篇!](https://mp.weixin.qq.com/s/_p7grwjISfMh0U65uOyCjA) 如果想系统学一学双指针的话, 可以看一下这篇[双指针法:总结篇!](https://mp.weixin.qq.com/s/_p7grwjISfMh0U65uOyCjA)