[LeetCode] 977. Squares of a Sorted Array

题:https://leetcode.com/problems/squares-of-a-sorted-array/

题目大意

对于非递减数组A,对所有元素的平方进行排序。

思路

元素的平方 较大的元素 只可能是 A中 很小的(负数)或 A中较大的元素。

于是使用双 指针,指向A 的 首元素 与 末尾元素。

比较两者的绝对值。

讲较大值放入 res 的末尾。

class Solution {
    public int[] sortedSquares(int[] A) {
        int[] res = new int[A.length];
        for(int pl = 0 , pr = A.length-1,pos = res.length -1;pl<=pr ;pos--){
            if(Math.abs(A[pl]) < Math.abs(A[pr]))
                res[pos] = A[pr]*A[pr--];
            else
                res[pos] = A[pl]*A[pl++];
            
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/86564204