leetcode 977. 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.

 

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.

题目大意:输入一个非递减序的数组,返回数组元素的平方,要求非递减序。

 

思路一:对每个元素平方操作,然后排序。

时间复杂度:O(nlogn),

空间复杂度:O(n)

 

思路二:考虑原数组是有序的,找到正负数的分解点,两个指针向左向右,比较。

 1 vector<int> sortedSquares(vector<int>& A) {
 2         vector<int> ans(A.size(), 0);
 3         int i = 0, len = A.size() - 1, k = 0;
 4         
 5         while (i < A.size() && A[i] < 0) ++i;
 6         
 7         int j = i - 1;
 8         while (j >= 0 && i <= len) {
 9             if (-A[j] < A[i]) {
10                 ans[k++] = A[j] * A[j];
11                 j--;
12             } else {
13                 ans[k++] = A[i] * A[i];
14                 i++;
15             }
16         }
17         while (j >= 0) {
18             ans[k++] = A[j] * A[j];
19             j--;
20         }
21         while (i <= len) {
22             ans[k++] = A[i] * A[i];
23             i++;
24         }
25         return ans;
26     }

或者直接从两端开始比较,此时大的数的平方肯定是最大的。

 1 vector<int> sortedSquares(vector<int>& A) {
 2         vector<int> ans(A.size(), 0);
 3         int i = 0, j = A.size() - 1, k = A.size() - 1;
 4         while (i <= j) {
 5             if (abs(A[i]) < abs(A[j])) {
 6                 ans[k--] = A[j] * A[j];
 7                 --j;
 8             } else {
 9                 ans[k--] = A[i] * A[i];
10                 ++i;
11             }
12         }
13         return ans;
14     }

 

你可能感兴趣的:(leetcode 977. Squares of a Sorted Array)