Let's talk about the mountain array in php

醉折花枝作酒筹
Release: 2023-03-11 10:24:02
forward
1672 people have browsed it

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
Copy after login

Example 2:

输入:[3,5,5]
输出:false
Copy after login

Example 3:

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

Tips:

  • 0 <= A.length <= 10000

  • ##0 <= A[i] <= 10000
  • # #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;
    }}
Copy after login

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!

Related labels:
php
source:hxd.life
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template