Leetcode 977 Squares of 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. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A is sorted in non-decreasing order.

解题思路

二次函数,中间低,两端高,从两端开始进行比较。
绝对值大的那个也是全局最大的。其乘方放在返回数组的最后一位,依次类推。

题解

    public int[] sortedSquares(int[] A) {
       
        int n = A.length;
        // 比较两端的绝对值 i 左  j右
        int i=0,j=n-1;
        int[] res = new int[n];
       // k表示放回数组的第k个数找到。
       // 这种左右开弓的方法 跟一轮快排还是很像。
        for (int k = n-1; k>=0; k--) {
            // 最大的放在后边
            if (Math.abs(A[i]) > Math.abs(A[j])){
                res[k] = A[i]*A[i];
                i++;
            }
            else {
                res[k] = A[j]*A[j];
                j--;
            }
        }
        return res;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,170评论 0赞 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 12,088评论 0赞 23
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 10,042评论 0赞 13
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 3,465评论 0赞 3
  • I feel so down and cannot shake it off. Whenever can I be...
    Elsachou阅读 218评论 0赞 0

友情链接更多精彩内容