Home  >  Article  >  Backend Development  >  Let's talk about the mountain array in php

Let's talk about the mountain array in php

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-07-07 15:27:351682browse

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.

Let's talk about the mountain array in php

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:

Lets talk about the mountain array in php

A.length >= 3

Under the condition of 0

  • A[0]

  • ##A[i] > A[i 1] > … > A[A.length - 1]

Example 1:

输入:[2,1]
输出:false

Example 2:

输入:[3,5,5]
输出:false

Example 3:

输入:[0,3,2,1]
输出:true

Tips:

  • 0
  • ##0

    # #Problem-solving ideas

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;
    }}

Recommended learning:

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!

Statement:
This article is reproduced at:hxd.life. If there is any infringement, please contact admin@php.cn delete