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