File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
LeetCode/977. Squares of a Sorted Array Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ var sortedSquares = function ( nums ) {
2
+ if ( nums . length === 1 ) return [ Math . pow ( nums [ 0 ] , 2 ) ] ;
3
+ let firstPositiveIdx = - 1 ;
4
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
5
+ if ( nums [ i ] >= 0 ) {
6
+ firstPositiveIdx = i ;
7
+ break ;
8
+ }
9
+ }
10
+ let squares = nums . map ( item => Math . pow ( item , 2 ) ) ;
11
+ let result = [ ] ;
12
+
13
+ if ( nums [ 0 ] >= 0 ) {
14
+ return squares ;
15
+ } else if ( nums [ nums . length - 1 ] <= 0 ) {
16
+ return squares . reverse ( ) ;
17
+ } else {
18
+ let first = firstPositiveIdx - 1 , second = firstPositiveIdx ;
19
+ while ( first >= 0 && second < nums . length ) {
20
+ if ( squares [ first ] <= squares [ second ] ) {
21
+ result . push ( squares [ first ] ) ;
22
+ first -- ;
23
+ } else {
24
+ result . push ( squares [ second ] ) ;
25
+ second ++ ;
26
+ }
27
+ }
28
+ while ( first >= 0 ) {
29
+ result . push ( squares [ first ] ) ;
30
+ first -- ;
31
+ }
32
+ while ( second < nums . length ) {
33
+ result . push ( squares [ second ] ) ;
34
+ second ++ ;
35
+ }
36
+ }
37
+
38
+ return result ;
39
+ }
40
+
41
+ console . log ( sortedSquares ( [ - 3 , 0 , 2 ] ) ) ;
You can’t perform that action at this time.
0 commit comments