Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Solution {
- public int solution(int[] A, int[] B){
- List<Interval> intervals = getSortedArrayList(A, B);
- Interval firstInterval, secondInterval;
- int iterator = 0;
- while(iterator < intervals.size()-1){
- firstInterval = intervals.get(iterator);
- secondInterval = intervals.get(iterator+1);
- if(checkIfIntervalsOverlapping(firstInterval, secondInterval)){
- mergeTwoIntervalsInArrayList(iterator, intervals);
- }
- else{
- iterator++;
- }
- }
- return intervals.size();
- }
- private List<Interval> getSortedArrayList(int[] beginnings, int[] endings){
- List<Interval> sortedIntervals = new ArrayList<>();
- checkIfArraysHaveSameLength(beginnings, endings);
- for(int i = 0; i < beginnings.length; i++){
- sortedIntervals.add(new Interval(beginnings[i], endings[i]));
- }
- Collections.sort(sortedIntervals, (firstInterval, secondInterval) -> firstInterval.compareTo(secondInterval));
- return sortedIntervals;
- }
- private boolean checkIfArraysHaveSameLength(int[] beginnings, int[] endings){
- if(beginnings.length != endings.length){
- throw new NotMatchingLengths();
- }
- else{
- return true;
- }
- }
- private boolean checkIfIntervalsOverlapping(Interval first, Interval second){
- return first.getEnding() >= second.getBeginning();
- }
- private void mergeTwoIntervalsInArrayList(int index, List<Interval> intervals){
- Integer newBeginning = intervals.get(index).getBeginning();
- Integer newEnding = intervals.get(index+1).getEnding();
- Interval mergedInterval = new Interval(newBeginning, newEnding);
- intervals.set(index, mergedInterval);
- intervals.remove(index+1);
- }
- public static void main(String[] args){
- Solution solution = new Solution();
- int result = solution.solution(new int[]{1, 12, 42, 70, 36, -4, 43, 15}, new int[]{5, 15, 44, 72, 36, 2, 69, 24});
- System.out.println(result);
- }
- }
- class Interval implements Comparable<Interval>{
- private Integer beginning;
- private Integer ending;
- public Integer getBeginning() {
- return beginning;
- }
- public Integer getEnding(){
- return ending;
- }
- public Interval(Integer beginning, Integer ending){
- this.beginning = beginning;
- this.ending = ending;
- }
- @Override
- public int compareTo(Interval that){
- Integer beginningsCompared = this.beginning.compareTo(that.beginning);
- return beginningsCompared;
- }
- }
- class NotMatchingLengths extends RuntimeException{
- public NotMatchingLengths(){
- super("Arrays have different lengths");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement