zoukankan      html  css  js  c++  java
  • 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]
     
    
    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 

  • 相关阅读:
    牛牛的揠苗助长(二分)
    树型DP简单入门
    Rational Ratio(一道思维题)
    Tima goes to Xentopia(条件最短路)
    中国剩余定理
    求解逆元的三种方法
    samba 基本配置及自定义控制
    vue之虚拟DOM、diff算法
    vue-cli3构建ts项目
    VMware+node+nginx+vue
  • 原文地址:https://www.cnblogs.com/pursuiting/p/10424040.html
Copyright © 2011-2022 走看看