1
+ /**
2
+
3
+ Time Complexity: O(n), Space Complexity O(n).
4
+
5
+ Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
6
+
7
+ Input: nums = [-4,-1,0,3,10]
8
+ Output: [0,1,9,16,100]
9
+
10
+ Input: nums = [-7,-3,2,3,11]
11
+ Output: [4,9,9,49,121]
12
+
13
+
14
+ Input: nums = [2,3,11]
15
+ Output: [4,9,121]
16
+
17
+ **/
18
+
19
+ class Solution {
20
+ public int [] sortedSquares (int [] nums ) {
21
+
22
+ int hasNegative = -1 ; // -1 Indcating that are no negative values in the input array.
23
+ int len = nums .length ;
24
+
25
+ // Find the index of the last negative value.
26
+ for (int i = 0 ; i < len ; ++i )
27
+ {
28
+ if (nums [i ] < 0 )
29
+ {
30
+ nums [i ] = Math .abs (nums [i ]); // If there is a negative value make it positive.
31
+ hasNegative = i ;
32
+ }
33
+ }
34
+
35
+
36
+ int []ans = new int [nums .length ];
37
+
38
+ if (hasNegative != -1 ) // check if the array have negative values
39
+ {
40
+
41
+ /**
42
+ If there are negative values,
43
+ that's divide the input array into two halfs.
44
+ both halfs are sorted in increasing order if:
45
+
46
+ -first half start from a and end at index 0, Where a is the index of the last negative value.
47
+ -second half start from (b) and end at (size of the array - 1 (n - 1)) [b, n-1] iclusive, Where b is the index a + 1.
48
+
49
+ At every step we choose the minimun value between the vlaues at index a and b then,
50
+ square the value and store it in array []ans.
51
+ **/
52
+ int a = hasNegative , b = hasNegative + 1 ;
53
+ int k = 0 ;
54
+
55
+ while (a >= 0 && b < len )
56
+ {
57
+ if (nums [a ] <= nums [b ]) // Value at index a is the minimum value so we choosed.
58
+ {
59
+ ans [k ] = nums [a ] * nums [a ];
60
+ a --;
61
+ }
62
+ else
63
+ {
64
+ ans [k ] = nums [b ] * nums [b ];
65
+ b ++;
66
+ }
67
+ k ++;
68
+ }
69
+
70
+ while (a >= 0 )
71
+ {
72
+ ans [k ++] = nums [a ] * nums [a ];
73
+ a --;
74
+ }
75
+
76
+ while (b < len )
77
+ {
78
+ ans [k ++] = nums [b ] * nums [b ];
79
+ b ++;
80
+ }
81
+ }
82
+ else //If there are no negative values, the sloution is straight forward.
83
+ {
84
+
85
+ for (int i = 0 ; i < len ; ++i )
86
+ ans [i ] = nums [i ] * nums [i ];
87
+ }
88
+ return ans ;
89
+ }
90
+
91
+ }
0 commit comments