File tree 1 file changed +14
-22
lines changed
1 file changed +14
-22
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int [] sortedSquares (int [] nums ) {
3
- int negativeIdx = 0 ;
4
- int positiveIdx = nums . length - 1 ;
5
- int [] result = new int [ nums . length ] ;
6
- int resultIdx = nums . length - 1 ;
7
- while ( resultIdx >= 0 ) {
8
- if ( nums [ negativeIdx ] < 0 && nums [positiveIdx ] >= 0 ) {
9
- if ( Math . abs ( nums [ negativeIdx ]) > nums [positiveIdx ]) {
10
- result [ resultIdx --] = nums [ negativeIdx ] * nums [ negativeIdx ] ;
11
- negativeIdx ++;
12
- } else {
13
- result [ resultIdx --] = nums [ positiveIdx ] * nums [ positiveIdx ] ;
14
- positiveIdx --;
2
+ public int [] sortedSquares (int [] nums ) {
3
+ int n = nums . length ;
4
+ int start = 0 ;
5
+ int end = n - 1 ;
6
+ int [] result = new int [ n ] ;
7
+ for ( int i = n - 1 ; i >= 0 ; i -- ) {
8
+ if ( Math . abs ( nums [start ]) >= Math . abs ( nums [ end ]) ) {
9
+ result [ i ] = nums [start ] * nums [ start ];
10
+ start ++ ;
11
+ } else {
12
+ result [ i ] = nums [ end ] * nums [ end ];
13
+ end -- ;
14
+ }
15
15
}
16
- } else if (nums [negativeIdx ] < 0 && nums [positiveIdx ] < 0 ) {
17
- result [resultIdx --] = nums [negativeIdx ] * nums [negativeIdx ];
18
- negativeIdx ++;
19
- } else {
20
- result [resultIdx --] = nums [positiveIdx ] * nums [positiveIdx ];
21
- positiveIdx --;
22
- }
16
+ return result ;
23
17
}
24
- return result ;
25
- }
26
18
}
You can’t perform that action at this time.
0 commit comments