layout: posttitle: PHP 实现有序数组的平方
subtitle: PHP 实现有序数组的平方
date: 2020-09-15
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode 977
- 双指针

有序数组的平方

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

示例 1:

  1. 输入:[-4,-1,0,3,10]
  2. 输出:[0,1,9,16,100]

示例 2:

  1. 输入:[-7,-3,2,3,11]
  2. 输出:[4,9,9,49,121]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array

解题思路 1

内置函数求解

代码
  1. class Solution {
  2. /**
  3. * @param Integer[] $A
  4. * @return Integer[]
  5. */
  6. function sortedSquares($A) {
  7. foreach ($A as &$item) {
  8. $item = $item * $item;
  9. }
  10. sort($A);
  11. return $A;
  12. }
  13. }

解题思路 2

双指针遍历,同时借助新数组,将计算平方之后的结果从大到小放到新数组。

  1. class Solution {
  2. /**
  3. * ** 2 为自乘 2 次,也是平方
  4. * @param Integer[] $A
  5. * @return Integer[]
  6. */
  7. function sortedSquares($A) {
  8. $ans = [];
  9. $i = 0;
  10. $j = count($A) - 1;
  11. $k = count($A) - 1;
  12. while ($i <= $j) {
  13. // 原数组是有序的,所以 -$A[$i] > $A[$j] 即为 $A[$i] 的绝对值平方后更大
  14. if (-$A[$i] > $A[$j]) {
  15. $ans[$k--] = $A[$i] ** 2;
  16. // 左指针向右移动
  17. $i++;
  18. } else {
  19. $ans[$k--] = $A[$j] ** 2;
  20. $j--;
  21. }
  22. }
  23. return $ans;
  24. }
  25. }

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券