欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

有序数组的平方(Squares of a Sorted Array)javascript

程序员文章站 2022-03-08 15:46:40
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.示例 1:输入:[-4,-1,0,3,10]输出:[0,1,9,16,100]Example 1:Input: nums = [...

题目来自于:https://leetcode-cn.com/problems/squares-of-a-sorted-array/

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

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

示例 1:

输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]

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].

示例 2:

输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

提示:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。

Constraints:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
    var B = [];
    //先获取nums数组每一项平方之后的数组B
    for (let i = 0; i < nums.length; i++) {
        B.push(nums[i]*nums[i]);
    }
    //再将B数组进行升序排列
    B.sort(function(a,b){
        return a-b;
    })
    return B;
};

本文地址:https://blog.csdn.net/ingenuou_/article/details/111117055