1
1
package leetcodeTags .array ;
2
2
3
+ import java .util .ArrayList ;
3
4
import java .util .Arrays ;
4
5
5
6
public class SquaresOfASortedArray977 {
6
7
8
+ // O(NlogN) time, O(N) space
7
9
public static int [] sortedSquares (int [] nums ) {
8
10
9
11
int [] output = new int [nums .length ];
@@ -16,9 +18,68 @@ public static int[] sortedSquares(int[] nums) {
16
18
return output ;
17
19
}
18
20
21
+ // follow up part - O(N) Time | O(N) Space
22
+ public static int [] sortedSquares2 (int [] nums ) {
23
+
24
+ ArrayList <Integer > list1 = new ArrayList <>(); // to store negative items
25
+ ArrayList <Integer > list2 = new ArrayList <>(); // to store positive items
26
+ int [] output = new int [nums .length ]; // to store final sorted array
27
+
28
+ for (int n : nums ) {
29
+ if (n < 0 ) {
30
+ list1 .add (n );
31
+ } else {
32
+ list2 .add (n );
33
+ }
34
+ }
35
+
36
+ int pos = 0 ; // position to fill in output array
37
+ int ptr1 = list1 .size () - 1 , ptr2 = 0 ;
38
+
39
+ /*
40
+ * here we traverse in reverse for list1 as it has negative elements in
41
+ * sorted order and from beginning for list2 as it has positive elements
42
+ */
43
+ while (ptr1 >= 0 && ptr2 < list2 .size ()) {
44
+ if (Math .abs (list1 .get (ptr1 )) < Math .abs (list2 .get (ptr2 ))) {
45
+ output [pos ] = list1 .get (ptr1 );
46
+ ptr1 --;
47
+ } else {
48
+ output [pos ] = list2 .get (ptr2 );
49
+ ptr2 ++;
50
+ }
51
+ pos ++;
52
+ }
53
+
54
+ // for remaining elements in either of two lists
55
+ while (pos < output .length && ptr1 >= 0 ) {
56
+ output [pos ] = list1 .get (ptr1 );
57
+ ptr1 --;
58
+ pos ++;
59
+ }
60
+ while (pos < output .length && ptr2 < list2 .size ()) {
61
+ output [pos ] = list2 .get (ptr2 );
62
+ ptr2 ++;
63
+ pos ++;
64
+ }
65
+
66
+ // squaring the sorted elements
67
+ for (int i = 0 ; i < output .length ; i ++) {
68
+ output [i ] = output [i ] * output [i ];
69
+ }
70
+
71
+ return output ;
72
+ }
73
+
19
74
public static void main (String [] args ) {
20
75
System .out .println (Arrays .toString (sortedSquares (new int [] { -4 , -1 , 0 , 3 , 10 })));
21
76
System .out .println (Arrays .toString (sortedSquares (new int [] { -7 , -3 , 2 , 3 , 11 })));
22
77
78
+ System .out .println ("\n testing optimal code\n " );
79
+ System .out .println (Arrays .toString (sortedSquares2 (new int [] { -4 , -1 , 0 , 3 , 10 })));
80
+ System .out .println (Arrays .toString (sortedSquares2 (new int [] { -7 , -3 , 2 , 3 , 11 })));
81
+
82
+ int [] arr = { -10 , -6 , -5 , -4 , -3 , -2 , -1 , 0 , 1 , 2 , 3 };
83
+ System .out .println (Arrays .toString (sortedSquares2 (arr )));
23
84
}
24
85
}
0 commit comments