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] <= 104numsis sorted in non-decreasing order.
這道題給了一個非降序排列的數組,可以有負數存在,現在讓求出每個數字的平方數,並且也是非降序排列。若數組中只有正數存在的話,則平方后的數組跟原數組的順序還是相同的。但是負數的平方是正數,則順序就會被打亂。最簡單暴力的方法就是把平方數存入一個 TreeSet,利用其自動排序的功能可以得到所求的順序了,注意這里需要用 multiset,因為可能存在重復值,參見代碼如下:
解法一:
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
類似題目:
參考資料:
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)
