forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 0977-squares-of-a-sorted-array.js
- Loading branch information
1 parent
e2aab2b
commit b393feb
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/** | ||
* @param {number[]} nums | ||
* @return {number[]} | ||
*/ | ||
var sortedSquares = function (nums) { | ||
let left = 0; | ||
let right = nums.length - 1; | ||
|
||
const answer = []; | ||
|
||
while (left <= right) { | ||
const leftSqr = Math.pow(nums[left], 2); | ||
const rightSqr = Math.pow(nums[right], 2); | ||
|
||
if (leftSqr > rightSqr) { | ||
answer.push(leftSqr); | ||
left++; | ||
} else { | ||
answer.push(rightSqr); | ||
right--; | ||
} | ||
} | ||
return answer.reverse(); | ||
}; |