LeetCode题解(0977):有序数组的平方(Python)
发布日期:2021-06-29 19:55:04
浏览次数:4
分类:技术文章
本文共 906 字,大约阅读时间需要 3 分钟。
题目:(简单)
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( N l o g N ) O(NlogN) O(NlogN) | O ( N ) O(N) O(N) | 240ms (98.34%) |
Ans 2 (Python) | O ( N ) O(N) O(N) | O ( N ) O(N) O(N) | 304ms (41.04%) |
Ans 3 (Python) |
LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。
解法一(Pythonic排序法):
def sortedSquares(self, A: List[int]) -> List[int]: return sorted([a*a for a in A])
解法二(双指针):
def sortedSquares(self, A: List[int]) -> List[int]: size = len(A) idx2 = 0 while idx2 < size and A[idx2] < 0: idx2 += 1 idx1 = idx2 - 1 ans = [] while 0 <= idx1 and idx2 <= size - 1: p1 = A[idx1] ** 2 p2 = A[idx2] ** 2 if p1 < p2: ans.append(p1) idx1 -= 1 else: ans.append(p2) idx2 += 1 while 0 <= idx1: ans.append(A[idx1] ** 2) idx1 -= 1 while idx2 <= size - 1: ans.append(A[idx2] ** 2) idx2 += 1 return ans
转载地址:https://dataartist.blog.csdn.net/article/details/107097482 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月30日 05时37分01秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
算法-动态规划
2019-04-30
算法-3个水桶8升水
2019-04-30
算法-稳定匹配
2019-04-30
管道堵住问题的定位
2019-04-30
ssh问题
2019-04-30
struct union and endian
2019-04-30
a bug related with extern
2019-04-30
cbwfq移植的思考
2019-04-30
TCE1保序功能的开发
2019-04-30
TCE1保序功能开发-----续
2019-04-30
低温故障处理
2019-04-30
联想G455 XP/MAC 双系统安装
2019-04-30
学习cocoa编程-.Cocoa.Programming
2019-04-30
第3章 Object c
2019-04-30
第4章 memory management
2019-04-30
第5章 target/action
2019-04-30
第6章 helper object
2019-04-30
第7章 Key-Value Coding; Key-Value Observing
2019-04-30
第8章 NSArrayController
2019-04-30
第9章 NSUndoManager
2019-04-30