# 977. Squares of a Sorted Array

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/squares-of-a-sorted-array/

> 内容描述

```
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

 

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
 

Note:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(N)******




```python
class Solution:
    def sortedSquares(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        return sorted([i**2 for i in A])
```


> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

two pointers

```python
class Solution:
    def sortedSquares(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        negatives, positives = [], []
        for i in A:
            if i < 0:
                negatives.append(i**2)
            else:
                positives.append(i**2)
        negatives = negatives[::-1]
        i, j = 0, 0
        res = []
        while i < len(negatives) and j < len(positives):
            if negatives[i] > positives[j]:
                res.append(positives[j])
                j += 1
            else:
                res.append(negatives[i])
                i += 1
        res.extend(positives[j:])
        res.extend(negatives[i:])
        return res
```




















































