关注 每天一道编程题 专栏,一起学习进步。

题目

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

分析

题意:给一个<mark>非递减</mark>数组(意思是递增?),返回其平方后的升序数组。
题目很简单,但是设计一个巧妙的方法降低复杂度才是最难的。

既然是递增数组,现然,平方值从0的左右向外蔓延,值越来越大,因此我们可以用两个指针进行双端遍历,且只需要比较绝对值即可。

算法:
头指针a指向数组A[0]
尾指针b指向数组A[n-1]
当头部绝对值比尾部绝对值大时,将头部平方存入结果集,然后将头指针++;
当尾部结对之比头部结对之大时,将尾部平方存入结果集,然后将尾指针–;
重复上述操作直到结果集被填满。

解答

class Solution {
    public int[] sortedSquares(int[] A) {
        int n = A.length;
        //结果集
        int[] res = new int[n];
        //头指针
        int a=0;
        //尾指针
        int b=n-1;
        //用于指向当前存放位置
        int p=n-1;
        for(;p>=0;){
            if(Math.abs(A[b])>Math.abs(A[a])){
                res[p--]=A[b]*A[b];
                b--;
            }else{
                res[p--]=A[a]*A[a];
                a++;
            }
        }
        return res;
    }
}