LeetCode题解(0977):有序数组的平方(Python)
发布日期:2021-06-29 19:55:04 浏览次数:3 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(0985):查询后的偶数和(Python)
下一篇:LeetCode题解(0976):三角形的最大周长(Python)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月14日 10时13分36秒