From 3be442c833eb21e1d7084cc44a898bf4ef951627 Mon Sep 17 00:00:00 2001 From: posper Date: Wed, 28 Jul 2021 14:47:26 +0800 Subject: [PATCH] =?UTF-8?q?0941.=E6=9C=89=E6=95=88=E7=9A=84=E5=B1=B1?= =?UTF-8?q?=E8=84=89=E6=95=B0=E7=BB=84=20=E6=B7=BB=E5=8A=A0Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0941.有效的山脉数组.md | 31 ++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/problems/0941.有效的山脉数组.md b/problems/0941.有效的山脉数组.md index 6dbc3da2..167cfb1a 100644 --- a/problems/0941.有效的山脉数组.md +++ b/problems/0941.有效的山脉数组.md @@ -18,7 +18,7 @@ https://leetcode-cn.com/problems/valid-mountain-array/ C++代码如下: -``` +```c++ class Solution { public: bool validMountainArray(vector& 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) -