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.

水题,没什么好说的,普遍两种方法;

其一:直接对原有数组元素平方,利用sort函数排序

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        for(int i=0;i<A.size();i++){
            A[i]=A[i]*A[i];
        }
        sort(A.begin(),A.end());
        return A;
    }
};

其二:设置头尾两个索引,同时来进行比较。头索引用来验证负数取正时是否可以大于尾索引指向的值,尾索引做一个从右到左的枚举;

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

猜你喜欢

转载自blog.csdn.net/InNoVaion_yu/article/details/88351840