Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
435 java solution
  • Loading branch information
ProgrammingPete committed Apr 3, 2022
commit d6065336acf0ff333cdacc5220df79ed78dbd44c
32 changes: 32 additions & 0 deletions java/435-Non-Overlapping-Intervals.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
int intervalsRemoved = 0;

//sort by the first vale in the intervals least to greatest
Arrays.sort(intervals, (arr1,arr2) -> Integer.compare(arr1[0], arr2[0]));
System.out.println(Arrays.deepToString(intervals));

//get the first interval
int[] intervalFirst = intervals[0];

// then loop through the rest of the intervals
for(int i = 1; i < intervals.length; i++){
if(firstIntervalwithinSecond(intervalFirst, intervals[i])){
//mark first interval to be removed
intervalsRemoved++;
// determine which interval to remove
//remove the interval that ends last
if(intervalFirst[1] > intervals[i][1]){
intervalFirst = intervals[i];
}
} else {
intervalFirst = intervals[i];
}
}
return intervalsRemoved;
}

public boolean firstIntervalwithinSecond(int[] intervalFirst, int[] intervalSecond){
return intervalSecond[0] < intervalFirst[1];
}
}