text: Nearest power of 2 of nearest perfect squares of non | Java program for the above approach ; Function to find nearest perfect square of num ; Calculate square root of num ; Calculate perfect square ; Find the nearest perfect square ; Function to find the power of 2 nearest to the number num ; Calculate log base 2 of num ; Highest power of 2 which is <= num ; Function to find the nearest perfect square and the nearest power of 2 of every array element whose occurrence is 1 ; Stores frequency of array elements ; Traverse the array and update frequency of current array element ; Traverse the map freq ; If the frequency is 1 ; Find nearest perfect square ; Print the nearest power of 2 ; If the any does not contain any non - repeating elements ; Driver Code
code: import java . util . * ; class GFG { static int perfectSquare ( int num ) { int sr = ( int ) ( Math . sqrt ( num ) ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( num - a ) < ( b - num ) ) { return a ; } else { return b ; } } static int powerOfTwo ( int num ) { int lg = ( int ) ( Math . log ( num ) / Math . log ( 2 ) ) ; int p = ( int ) ( Math . pow ( 2 , lg ) ) ; return p ; } static void uniqueElement ( int arr [ ] , int N ) { boolean ans = true ; HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } for ( Map . Entry < Integer , Integer > el : freq . entrySet ( ) ) { if ( el . getValue ( ) == 1 ) { ans = false ; int ps = perfectSquare ( el . getKey ( ) ) ; System . out . print ( powerOfTwo ( ps ) + " ▁ " ) ; } } if ( ans ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 11 , 4 , 3 , 4 } ; int N = arr . length ; uniqueElement ( arr , N ) ; } }