---
description: 已經排序過 !! 這種題目東常都試用 Two pointer / 若可以用 two pointer 取代掉 sort()、 map 那是最好的了
---

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

