# 977. Squares of a Sorted Array

给定整数数组的按平方值排序。暴力法O(NlgN)，进一步优化=>O(N)。负数范围是一个排好序的序列，正数同样，每步都是按序从它们中各自最小或最大的选一个，因此用两个指针指向数组两边，每次选大的倒着插入到res。

```cpp
/*
 * @lc app=leetcode id=977 lang=cpp
 *
 * [977] Squares of a Sorted Array
 */

// @lc code=start
class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        const int N = A.size();
        vector<int> res(N, 0);
        for (int i = 0, j = N - 1, k = N - 1; k >= 0; --k) {
            if (abs(A[i]) < abs(A[j])) res[k] = A[j] * A[j--]; 
            else res[k] = A[i] * A[i++]; 
        } 
        return res;
    }
};
// @lc code=end


```


---

# Agent Instructions: 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://hao-fu-1.gitbook.io/oj/multiple-pointers/two_sum/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.
