You have a sorted array of integers. Write a function that returns a sorted array containing the squares of those integers.
Ex:-
[ -6, -4, 1, 2, 3, 5 ]
output:-
[ 1, 4, 9, 16, 25, 36 ]
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.*; public class SquaredArray{ public static void main(String []args){ int[] arr = { -6, -4, 1, 2, 3, 5 }; int[] result = sortSquaredArray(arr); for(int x: result) System.out.print(x+" "); } public static int[] sortSquaredArray(int[] arr){ for(int i=0; i<arr.length; i++) arr[i] = arr[i] * arr[i] ; Arrays.sort(arr); return arr; } } |
Java ( Another approach )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.*; public class SquaredArray{ public static void main(String []args){ int[] arr = { -6, -4, 1, 2, 3, 5 }; int[] result = sortSquaredArray(arr); for(int x: result) System.out.print(x+" "); } public static int[] sortSquaredArray(int[] arr){ int[] result = new int[arr.length]; int left = 0, right = arr.length - 1; for(int i=arr.length-1; i>=0; i--){ if(Math.abs(arr[left]) > arr[right]){ result[i] = arr[left]*arr[left]; left++; } else{ result[i] = arr[right]*arr[right]; right--; } } return result; } } |
Python
arr = [ -6, -4, 1, 2, 3, 5 ] for i in range(0,len(arr)): arr[i] = arr[i]*arr[i] arr.sort() print(arr)