Closest greater element for every array element from another array | Java to find result from target array for closest element ; Function for printing resultant array ; change arr [ ] to Set ; vector for result ; calculate resultant array ; check upper bound element ; if no element found push - 1 ; Else push the element ; add to resultant ; Driver Code
import java . util . * ; class GFG { static void closestResult ( Integer [ ] a , int [ ] b , int n ) { TreeSet < Integer > vect = new TreeSet < > ( Arrays . asList ( a ) ) ; Vector < Integer > c = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Integer up = vect . higher ( b [ i ] ) ; if ( up == null ) c . add ( - 1 ) ; else c . add ( up ) ; } System . out . print ( " Result ▁ = ▁ " ) ; for ( int i : c ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { Integer [ ] a = { 2 , 5 , 6 , 1 , 8 , 9 } ; int [ ] b = { 2 , 1 , 0 , 5 , 4 , 9 } ; int n = a . length ; closestResult ( a , b , n ) ; } }