In php, I wonder if you have heard of such an array called a mountain array. Today we will introduce the mountain array in detail. Friends in need can refer to it.
Valid mountain array
Given an integer array A, return true if it is a valid mountain array, otherwise Return false.
Let's review that A is an array of mountains if it satisfies the following conditions:
A.length >= 3
Under the condition of 0
A[0]
输入:[2,1] 输出:false
输入:[3,5,5] 输出:false
输入:[0,3,2,1] 输出:true
One of the two pointers runs from front to back, and the other runs from back to front. As long as they can eventually meet in the middle.
Note the critical condition: If left or right does not move, it means that it is a monotonically increasing or decreasing array, and it is still not a mountain.class Solution { /** * @param Integer[] $A * @return Boolean */ function validMountainArray($A) { if (count($A) < 3) return false; $left = 0; $right = count($A) - 1; // 注意防止越界 while ($left < count($A) - 1 && $A[$left] < $A[$left + 1]) $left++; // 注意防止越界 while ($right > 0 && $A[$right] < $A[$right - 1]) $right--; // 如果left或者right都在起始位置,说明不是山峰 if ($left == $right && $left != 0 && $right != count($A) - 1) return true; return false; }}
php video tutorial
The above is the detailed content of Let's talk about the mountain array in php. For more information, please follow other related articles on the PHP Chinese website!