【LeetCode】有序数组的平方

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

 

示例 1:

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

示例 2:

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

 

提示:

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

思路:

方法一:计算平方结果后排序

代码实现:

class Solution {
    public static int[] sortedSquares(int[] A) {

        for (int i=0;i<A.length;i++)    //求平方
            A[i] = A[i]*A[i];

        for (int i=0;i<A.length-1;i++)    //排序
            for (int j=0;j<A.length-i-1;j++)
                if (A[j]>A[j+1])
                {
                    int temp = A[j];
                    A[j] = A[j+1];
                    A[j+1] = temp;
                }
                
                return A;
    }
}

 

 

方法二:双指针,由于平方的特点,越小的负数的平方越大。所以可以维护原数组首位尾两个指针,判断指针对应元素的平方大小,将较大的一个平方数存入新数组末尾,然后指针前移,直到最终指针重合。

代码实现:

class Solution {
    public static int[] sortedSquares(int[] A) {

        int firstA = 0;                    //原数组首指针
        int lastA = A.length-1;            //原数组尾指针

        int []res = new int[A.length];    //结果数组
        int lastR = res.length-1;        //结果数组尾指针

        while(firstA<=lastA)
        {
            if (A[firstA]*A[firstA]>=A[lastA]*A[lastA])
            {
                res[lastR] = A[firstA]*A[firstA];
                firstA++;
                lastR--;
            }
            else
            {
                res[lastR] = A[lastA]*A[lastA];
                lastA--;
                lastR--;
            }
        }

        return res;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值