977. Squares of a Sorted Array

Given an integer array `nums` sorted in non-decreasing order, return  an array of the squares of each number sorted in non-decreasing order.

Example 1:

``````Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
``````

Example 2:

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

Constraints:

• `1 <= nums.length <= 104`
• `-104 <= nums[i] <= 104`
• `nums` is sorted in non-decreasing order.

``````class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
multiset<int> st;
for (int num : A) st.insert(num * num);
return vector<int>(st.begin(), st.end());
}
};
``````

``````class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int n = A.size(), i = 0, j = n - 1;
vector<int> res(n);
for (int k = n - 1; k >= 0; --k) {
if (abs(A[i]) > abs(A[j])) {
res[k] = A[i] * A[i];
++i;
} else {
res[k] = A[j] * A[j];
--j;
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/977

Sort Transformed Array

Merge Sorted Array

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

https://leetcode.com/problems/squares-of-a-sorted-array/discuss/221922/Java-two-pointers-O(N)

https://leetcode.com/problems/squares-of-a-sorted-array/discuss/495394/C%2B%2B%3A-Simplest-one-pass-two-pointers

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation