[Python] Squares of a Sorted Array: why sorted() method is faster than O(n) method? [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on LeetCode algorithm problem 977. Squares of a Sorted Array.

    Why are the submissions using the built-in method sorted faster than my O(n) traversal method as below?

    The input is a sorted (non-decreasing order) list with integers.

    Sample 208 ms submission:

    class Solution:
    def sortedSquares(self, A: List[int]) -> List[int]:
    return sorted(x*x for x in A)


    My 260 ms submission:

    class Solution:
    def sortedSquares(self, A: List[int]) -> List[int]:
    start = 0
    end = len(A)-1

    B = []

    while start <= end:
    if abs(A[start]) >= abs(A[end]):
    B.append(A[start] * A[start])
    start += 1
    else:
    B.append(A[end] * A[end])
    end -= 1
    B.reverse()
    return B

    Continue reading...

Compartilhe esta Página