Java- Return the Squares of a Sorted Array in Sorted Order
In this Java exercise, you have an integer array sorted in non-decreasing order, and you must return an array of the squares of each element sorted in non-decreasing order.
For example:
Input : [-4,-1,0,3,10]
Output : [16,1,0,9,100]
Final Result : [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].
1. Using Java 8
With JDK 8, you can use the Stream API and it’s map for squaring of each element and sorted method for the sorting of the result.
private static int[] sortedSquareUsingJava8(int[] nums) {
return Arrays.stream(nums).map(e -> e * e).sorted().toArray();
}
2. Using Java
public static int[] sortedSquares(int[] nums) {
for (int i = 0; i < nums.length; i++) {
// Square of element
nums[i] = nums[i] * nums[i];
}
// sort the array
Arrays.sort(nums);
return nums;
}