Home >Backend Development >PHP Problem >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, 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.
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]
Example 2:
输入:[-7,-3,2,3,11] 输出:[4,9,9,49,121]
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; }}
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; }}
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!