TreeSet is an example of Set Interface. Generally, it stores the elements in ascending order. It takes the elements with non-null value. It allows the multithreading.
Ceiling on the right-side Problem:
It is a problem which
checks the each element and the smallest element should be in right side.
Implementation:
Built in class: “TreeSet”
Functions:
- finditCeilingOnRight(): This function is used to traverse the array from the right to left side.
- Ceiling() : it checks the smallest with with current element.
- Add() :It inserts the element to the set.
Note :To update the ceiling value for result array ceil
variable is used.
Steps to implement the program:
- Include the built in package java.util.*;
- Create a class “CeilingONRightsolution” with main() function.
- Get the input array elements.
- Call the function “finditCeilingOnRight()” with input array and assign it to output array.
- finditCeilingOnRight() – It finds the length of array. check the each and every element.
- Based on the comparison, it assign the smallest value in right or -1.
- Add the values to output set.
- Finally, the output is printed.
Program:
import java.util.*;
public class CeilingONRightsolution {
public static void
main(String[] args) {
int[] arr1 =
{12, 18, 40, 5, 35, 87,23};
int[] output =
finditCeilingOnRight(arr1);
System.out.println("The
input array is: " + Arrays.toString(arr1));
System.out.println("The array after Ceiling on the right: " +
Arrays.toString(output));
}
int len =
arr1.length;
int[] output =
new int[len];
TreeSet<Integer> set1 = new TreeSet<>();
// iterating
the array from right to left
for (int i =
len - 1; i >= 0; i--) {
Integer
ceil = set1.ceiling(arr1[i]);
output[i]
= (ceil != null) ? ceil : -1;
set1.add(arr1[i]);
}
return output;
}
}
Output:
C:\raji\blog>javac CeilingONRightsolution.java
C:\raji\blog>java CeilingONRightsolution
The input array is: [12, 18, 40, 5, 35, 87, 23]
The array after Ceiling on the right: [18, 23, 87, 23, 87,
-1, -1]
This is the simple way of implementing this solution. Keep
coding!!!
No comments:
Post a Comment