Home > Backend Development > PHP Problem > How to implement square of ordered array in PHP

How to implement square of ordered array in PHP

醉折花枝作酒筹
Release: 2023-03-11 10:58:01
forward
2089 people have browsed it

Given an array A of integers sorted in non-decreasing order, return a new array consisting of the square of each number, which is also required to be sorted in non-decreasing order. Today, the editor will introduce the method of realizing the square of ordered array in PHP. You can refer to it if you need it.

How to implement square of ordered array in PHP

Given an array A of integers sorted in non-decreasing order, return a new array consisting of the square of each number, also sorted in non-decreasing order.

Example 1:

输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
Copy after login

Example 2:

输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
Copy after login

Solution idea 1

Built-in function solution

Code

class Solution {
    /** 
    * @param Integer[] $A 
    * @return Integer[] 
    */
    function sortedSquares($A) {
        foreach ($A as &$item) {
            $item = $item * $item;
        }
        sort($A);
        return $A;
    }}
Copy after login

Solution idea 2

Double pointer traversal, and with the help of the new array, after calculating the square The results are placed in the new array from large to small.

class Solution {
    /** 
    * 
    *
    * 2 为自乘 2 次,也是平方 
    * @param Integer[] $A 
    * @return Integer[] 
    */
    function sortedSquares($A) {
        $ans = [];
        $i = 0;
        $j = count($A) - 1;
        $k = count($A) - 1;
        while ($i <= $j) {
            // 原数组是有序的,所以 -$A[$i] > $A[$j] 即为 $A[$i] 的绝对值平方后更大 
            if (-$A[$i] > $A[$j]) {
                $ans[$k--] = $A[$i] ** 2;
                // 左指针向右移动
                
                $i++;
            } else {
                $ans[$k--] = $A[$j] ** 2;
                $j--;
            }
        }
        return $ans;
    }}
Copy after login

Recommended learning: php video tutorial

The above is the detailed content of How to implement square of ordered 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