I had this question in an interview recently. Given a sorted array of integers, return a list of those integers squared, with the squares sorted. So given an array of these numbers:
-5, -3, 1, 2, 4
the result should be this:
1 4 9 16 25
I came up with this solution using Java 8 streams, but is there a way to do this without the call to Array.sort
?
public static int[] sortedSquares(int[] arr) { arr = Arrays.stream(arr).map(i -> i * i).toArray(); Arrays.sort(arr); return arr; }
abs
.\$\endgroup\$abs
, just take the first nonnegative element and see how its sum with its previous element compares to zero.\$\endgroup\$