首页 > 其他 > 详细

977. Squares of a Sorted Array

时间:2019-02-23 20:23:32      阅读:162      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

思路:将数组中每个元素平方之后,最大的值肯定在数组的两侧,因此从数组两侧向中间查找即可。

参考代码:

#include <vector>
#include <iostream>

using namespace std;


class Solution {
 public:
  vector<int> sortedSquares(vector<int>& A) {
    vector<int> answer(A.size(), 0);
    int l = 0, r = A.size() - 1;
    int left, right;

    while (l <= r)
    {
        left = abs(A[l]);
        right = abs(A[r]);
        if (left < right)
        {
            answer[r - l] = right * right;
            r -= 1;
        }
        else
        {
            answer[r - l] = left * left;
            l += 1;
        }
    }

    return answer;
  }
};


int main()
{
    int a[] = {-4, -1, 0, 3, 10};
    Solution solu;
    vector<int> vec_arr(a, a+4);
    vector<int> ret = solu.sortedSquares(vec_arr);
    for (int i = 0; i < ret.size(); ++i)
    {
        cout << ret[i] << " ";
    }

    return 0;
}

运行结果:

0 1 9 16 

 

977. Squares of a Sorted Array

原文:https://www.cnblogs.com/pursuiting/p/10424040.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!