PHP如何实现有序数组平方排序的算法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计657个文字,预计阅读时间需要3分钟。
给定一个非递减顺序排列的整数数组A,返回每个数字的平方组成的新的数组,且新数组也需保持非递减顺序。
以下是一个PHP实现的示例:
phpfunction sortedSquares($A) { $n=count($A); $squares=array_fill(0, $n, 0); $left=0; $right=$n - 1; $index=$n - 1;
while ($left $A[$right] * $A[$right]) { $squares[$index]=$A[$left] * $A[$left]; $left++; } else { $squares[$index]=$A[$right] * $A[$right]; $right--; } $index--; }
return $squares;}
// 示例$A=[-4, -1, 0, 3, 10];$result=sortedSquares($A);print_r($result); // 输出: Array ( [0]=> 0 [1]=> 1 [2]=> 9 [3]=> 16 [4]=> 100 )
这段代码首先创建了一个与原数组长度相同的新数组`squares`,用于存储平方后的结果。然后使用双指针技术,一个从数组的左侧开始,另一个从右侧开始,比较两个指针指向的元素的平方,将较大的平方值放入`squares`数组的末尾,并移动相应的指针。这样,新数组`squares`在填充过程中始终保持非递减顺序。
给定一个按非递减顺序排序的整数数组A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。本文共计657个文字,预计阅读时间需要3分钟。
给定一个非递减顺序排列的整数数组A,返回每个数字的平方组成的新的数组,且新数组也需保持非递减顺序。
以下是一个PHP实现的示例:
phpfunction sortedSquares($A) { $n=count($A); $squares=array_fill(0, $n, 0); $left=0; $right=$n - 1; $index=$n - 1;
while ($left $A[$right] * $A[$right]) { $squares[$index]=$A[$left] * $A[$left]; $left++; } else { $squares[$index]=$A[$right] * $A[$right]; $right--; } $index--; }
return $squares;}
// 示例$A=[-4, -1, 0, 3, 10];$result=sortedSquares($A);print_r($result); // 输出: Array ( [0]=> 0 [1]=> 1 [2]=> 9 [3]=> 16 [4]=> 100 )
这段代码首先创建了一个与原数组长度相同的新数组`squares`,用于存储平方后的结果。然后使用双指针技术,一个从数组的左侧开始,另一个从右侧开始,比较两个指针指向的元素的平方,将较大的平方值放入`squares`数组的末尾,并移动相应的指针。这样,新数组`squares`在填充过程中始终保持非递减顺序。
给定一个按非递减顺序排序的整数数组A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
