25 Squares of a Sorted Array

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

题目

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.

分析

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

既然是递增数组,现然,平方值从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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值