[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;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值