mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
新增 0977 有序数组的平方 JavaScript版本 更加简洁高效的解法
This commit is contained in:
@ -199,27 +199,26 @@ impl Solution {
|
|||||||
Javascript:
|
Javascript:
|
||||||
```Javascript
|
```Javascript
|
||||||
/**
|
/**
|
||||||
* @desc two pointers solution
|
* @param {number[]} nums
|
||||||
* @link https://leetcode-cn.com/problems/squares-of-a-sorted-array/
|
* @return {number[]}
|
||||||
* @param nums Array e.g. [-4,-1,0,3,10]
|
|
||||||
* @return {array} e.g. [0,1,9,16,100]
|
|
||||||
*/
|
*/
|
||||||
const sortedSquares = function (nums) {
|
var sortedSquares = function(nums) {
|
||||||
let res = []
|
let n = nums.length;
|
||||||
for (let i = 0, j = nums.length - 1; i <= j;) {
|
let res = new Array(n).fill(0);
|
||||||
const left = Math.abs(nums[i])
|
let i = 0, j = n - 1, k = n - 1;
|
||||||
const right = Math.abs(nums[j])
|
while (i <= j) {
|
||||||
if (right > left) {
|
let left = nums[i] * nums[i],
|
||||||
// push element to the front of the array
|
right = nums[j] * nums[j];
|
||||||
res.unshift(right * right)
|
if (left < right) {
|
||||||
j--
|
res[k--] = right;
|
||||||
} else {
|
j--;
|
||||||
res.unshift(left * left)
|
} else {
|
||||||
i++
|
res[k--] = left;
|
||||||
}
|
i++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return res
|
return res;
|
||||||
}
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
Swift:
|
Swift:
|
||||||
|
Reference in New Issue
Block a user