977. 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]

原文链接:https://leetcode.com/problems/squares-of-a-sorted-array/


比较简单,给一个非递减的数组,数组中的数字有正也有负,然后需要把数组中的数字取平方并且从小到大进行排序并返回。


最简单的做法就是把数组中的所有数字取平方,然后对这个数组进行排序并返回。但是这样的话,就会对数组遍历两次(取平方一次,排序一次),明显效率不太高。

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        for(int i = 0; i < A.size(); i++) {
            A[i] *= A[i];// 平方
        }
        sort(A.begin(), A.end());
        return A;
    }
};

可以看到题目中说的数组是非递减的,这样看来最大的数在数组的最后面,那么最大的数平方之后也会是最大的,但是不要忘记了很小的负数平方之后也会有可能变成最大的,比如:- 9 的平方 = 81 > 8 的平方 = 64。
所以平方之后最大的数可能是在原数组的最前面(负数),也有可能是在原数组的最后面(正数),根据此特性,只需遍历一边数组即可。我们从原数组的两侧开始遍历,把平方之后较大的数放在新数组的最后,依次向中间靠拢计算即可。

// 利用非递减的特性
class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int left = 0;
        int right = A.size() - 1;
        int n = A.size() - 1; 
        vector<int> result(A.size(), 0); // 用来保存平方之后的数组
        while(left <= right) { // 平方最大的数字在数组的两侧
            if(abs(A[left]) < abs(A[right]))
                result[n--] = A[right]*A[right--];
            else
                result[n--] = A[left]*A[left++];
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值