Javascript 1 2 param number nums return number 5 let n = numslength; var sortedSquares = functionnums 搜索 6 let res = new Arraynfille; 8 leti=0j=n-1k=n-1; while i = j 10 let left = numsinumsi 11
This JavaScript code defines a function called "sortedSquares" that takes in an array of numbers called "nums" and returns a new array with each number squared and sorted in ascending order. The function first initializes a variable "n" to the length of the "nums" array. It then creates a new array called "res" with "n" elements and fills each element with the value of "e".
Next, the code defines three variables: "i" is initialized to 0, "j" is initialized to "n-1" (the last index of the "nums" array), and "k" is initialized to "n-1" (the last index of the "res" array). The code then enters a while loop that will continue as long as "i" is less than or equal to "j".
Within the while loop, the code calculates the square of the number at the current index of "i" and "j" and compares them. If the square of the number at index "i" is less than the square of the number at index "j", the code places the squared number at index "j" into the "res" array at index "k" and decrements "j" and "k". If the square of the number at index "i" is greater than or equal to the square of the number at index "j", the code places the squared number at index "i" into the "res" array at index "k" and increments "i" and decrements "k".
Once the while loop ends, the code returns the "res" array.
原文地址: http://www.cveoy.top/t/topic/bmaX 著作权归作者所有。请勿转载和采集!