码迷,mamicode.com
首页 > 其他好文 > 详细

977. Squares of a Sorted Array

时间:2021-04-08 13:55:44      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:result   math   square   each   input   --   length   public   return   

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-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 }

 

977. Squares of a Sorted Array

标签:result   math   square   each   input   --   length   public   return   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/14630313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!