Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

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.

 

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. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A is sorted in non-decreasing order.

Companies:
Google, Facebook, Adobe, Apple

Related Topics:
Array, Two Pointers, Sort

Solution 1.

// OJ: https://leetcode.com/problems/squares-of-a-sorted-array/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int i = 0, j = A.size() - 1, k = j;
        vector<int> ans(A.size());
        for (; i <= j; --k) {
            if (pow(A[i], 2) > pow(A[j], 2)) ans[k] = pow(A[i++], 2);
            else ans[k] = pow(A[j--], 2);
        }
        return ans;
    }
};