Squares of a Sorted Array

Posted beiyeqingteng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]

 1 class Solution 
 2     public int[] sortedSquares(int[] A) 
 3         int n = A.length;
 4         int[] result = new int[n];
 5         int i = 0, j = n - 1;
 6         for (int p = n - 1; p >= 0; p--) 
 7             if (Math.abs(A[i]) > Math.abs(A[j])) 
 8                 result[p] = A[i] * A[i];
 9                 i++;
10              else 
11                 result[p] = A[j] * A[j];
12                 j--;
13             
14         
15         return result;
16     
17 

 

 

以上是关于Squares of a Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

leetcode977. Squares of a Sorted Array

LeetCode 977 Squares of a Sorted Array

LeetCode 977. Squares of a Sorted Array

LeetCode 977 Squares of a Sorted Array 解题报告

LeetCode --- 977. Squares of a Sorted Array 解题报告

Leetcode_easy977. Squares of a Sorted Array