# #977 Squares of a Sorted Array

[LeetCode](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.

// 平方根完一定是正整數 eg -5*-5 = 25

input: array 是 ascending 的
output 全部轉平方根後 ascending
```

```
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.

*/

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortedSquares = function(A) {}
```

### 如何解

本來最直覺想法是用 map 都平方之後再用 sort ，但其實有效能更好解法

```
var sortedSquares = function(A) {
    // return A.map( item => {
    //     return Math.pow(item, 2)
    // }).sort( (a,b) => a - b)
};

console.log(sortedSquares([-7,-3,2,3,11]))
// faster than 50.52% of JavaScript online submissions
```

### 改善

因為已經排序過，就算有負數，頭尾一定是最大的，所以可以用 Two pointer 排序

```
var sortedSquares = function(A) {
    let head = 0;
    let tail = A.length - 1;
    let result = [];
    while(head <= tail){
        if(Math.pow(A[head], 2) < (Math.pow(A[tail], 2))){
            result.push(Math.pow(A[tail], 2))
            tail --;
        }else{
            result.push(Math.pow(A[head], 2))
            head ++;
        }
    }
    // reserve() 就可以了，不需要 sort，因為上面已經排序過了
    return result.reverse();
};

console.log(sortedSquares([-7,-3,2,3,11]))
// faster than 93.17% of JavaScript online submissions
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/two-pointer/977-squares-of-a-sorted-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
