977. Squares of a Sorted Array

问题:

给定一个非减数组,求对其每个元素进行平方运算后,形成的非减数组。

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

  

解法:

定义两个游标

l:从原数组index=0开始递增

h:从原数组index=end开始递减。

依次比较A[l]和A[h]的绝对值abs,把较大者计算平方,放入结果数组的最后。

(结果数组从后往前进行赋值)

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> sortedSquares(vector<int>& A) {
 4         int l=0, h=A.size()-1, i=A.size()-1;
 5         vector<int> res(A.size(),0);
 6         while(i>=0){
 7             if(abs(A[l])>abs(A[h])){
 8                 res[i]=A[l]*A[l];
 9                 i--, l++;
10             }else if(abs(A[l])<abs(A[h])){
11                 res[i]=A[h]*A[h];
12                 i--, h--;
13             }else if(abs(A[l])==abs(A[h])){
14                 res[i--]=A[h]*A[h];
15                 if(i<0) break;
16                 res[i]=res[i+1];
17                 i--;
18                 h--,l++;
19             }
20         }
21         return res;
22     }
23 };
原文地址:https://www.cnblogs.com/habibah-chang/p/12997286.html