[leetcode/lintcode 题解]字节跳动面试题:有序数组的平方

416 阅读1分钟

【题目描述】 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。

在线评测地址:LintCode 领扣

样例

示例1

输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]

示例2

输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]

【题解】

先循环遍历数组A,得到该数组每个位置数所对应的平方数,然后排序即可

public class Solution {
    /**
     * @param A: The array A.
     * @return: The array of the squares.
     */
    public int[] SquareArray(int[] A) {
        for(int i = 0; i < A.length ; i++){
            A[i] = A[i] * A[i];
        } 
        Arrays.sort(A);
        return A;
    }
}

更多语言代码参见:leetcode/lintcode 题解