当前位置:网站首页>【力扣】977. 有序数组的平方
【力扣】977. 有序数组的平方
2022-06-28 15:59:00 【e1373773】
这道题大致有两种方法,一种是先循环再排序,一种是双指针比较后排序。
大家平时工作中会用哪种方法,请评论区告诉up,谢谢。
方法一: 普通先循环再排序(PHP)
class Solution {
/**
* @param Integer[] $nums
* @return Integer[]
*/
function sortedSquares($nums) {
foreach($nums as &$value) {
$value = $value * $value;
}
unset($value);
asort($nums);
return $nums;
}
}解释: 利用PHP里的数组引用赋值 "&" 而非拷贝赋值方法,减少空间复杂度。
测试结果:
执行用时:72 ms, 在所有 PHP 提交中击败了59.44%的用户
内存消耗:18.3 MB, 在所有 PHP 提交中击败了6.29%的用户
通过测试用例:137 / 137
方法二: 利用双指针(PHP)
class Solution {
/**
* @param Integer[] $nums
* @return Integer[]
*/
function sortedSquares($nums) {
$length = count($nums) - 1;
$res = [];
$res = array_pad($res, $length, 1);
for($i = 0, $j = $length, $pos = $length; $i <= $j; ) {
if ($nums[$i] * $nums[$i] > $nums[$j] * $nums[$j]) {
$res[$pos] = $nums[$i] * $nums[$i];
++$i;
} else {
$res[$pos] = $nums[$j] * $nums[$j];
--$j;
}
--$pos;
}
return $res;
}
}解释: PHP在创建数组是不指定数组长度,是不是不能通过下标来插入元素。。。这里使用了 array_pad 来指定数组长度并且填充了占位元素。
测试结果:
执行用时:64 ms, 在所有 PHP 提交中击败了86.01%的用户
内存消耗:17.8 MB, 在所有 PHP 提交中击败了69.23%的用户
通过测试用例:137 / 137
边栏推荐
- 扎克伯格致投资者:不要对元宇宙有任何期待
- No win32/com in vs2013 help document
- Deep learning convolutional neural network of machine learning to realize handwritten font recognition based on CNN network
- Convolutional neural networks for machine learning -- an introduction to CNN
- VS2013 帮助文档中没有 win32/com
- Slim GAIN(SGAIN)介绍及代码实现——基于生成对抗网络的缺失数据填补
- Naacl 2022 | distillation of machinetranslation SOTA model
- 运动App如何实现端侧后台保活,让运动记录更完整?
- 10年测试经验,在35岁的生理年龄面前,一文不值
- tablestore中可以使用sql查询可以查出表中所有的数据吗?
猜你喜欢

Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills

Azure Kinect Microsoft camera unity development summary

【Proteus仿真】L297驱动步进电机

知道这几个命令让你掌握Shell自带工具

Big God explains open source buff gain strategy live lecture
PostgreSQL enables grouping statistics by year, month, day, week, hour, minute and second

What is the maximum number of concurrent TCP connections for a server? 65535?

Internet of things cloud convergence Security Guide

榜单首发——线控制动「新周期」,本土供应商市场竞争力TOP10

Slim gain (sgain) introduction and code implementation -- missing data filling based on generated countermeasure network
随机推荐
REDIS00_详解redis.conf配置文件
leetcode:22. bracket-generating
QT interface library
Tiktok actual battle ~ list of bloggers I follow, follow and check
#夏日挑战赛#OHOS构建自定义服务实战
Qt5.5.1配置MSVC2010编绎器和windbg调试器
超自动化与网络安全的未来
逆向调试入门-PE结构详解02/07
The first place on the list - brake by wire "new cycle", the market competitiveness of local suppliers is TOP10
征文投稿丨使用轻量应用服务器搭建博客环境
防火墙基础之流量管理与控制
Steps to be taken for successful migration to the cloud
零钱兑换(动态规划)
ID card copy tutorial (use t5577 card to copy 4100 card)
What are the most powerful small and medium-sized companies in Beijing?
Opengauss kernel: analysis of SQL parsing process
一次简单的反射型XSS操作及思路
GAIN的代码实现(4)——基于GAN的Spam数据集缺失数据填补(序)【改进版】
访中国信通院王蕴韬:数实融合赋能文化产业繁荣发展
Introduction to deep learning in machine learning