https://leetcode.com/problems/insert-interval/description/
You are given an array of non-overlapping intervals intervals
where intervals[i] = [starti, endi]
represent the start and the end of the ith
interval and intervals
is sorted in ascending order by starti
. You are also given an interval newInterval = [start, end]
that represents the start and end of another interval.
Insert newInterval
into intervals
such that intervals
is still sorted in ascending order by starti
and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals
after the insertion.
Example 1:
1 2 |
<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5] <strong>Output:</strong> [[1,5],[6,9]] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> res = new ArrayList<>(); //add newInterval to the list res.add(newInterval); //add intervals to the list for(int[] i: intervals){ res.add(i); } //sort the list by ascending order by start Collections.sort(res, new Comparator<int[]>(){ public int compare(int[] a, int[] b){ return Integer.compare(a[0], b[0]); } }); int[] prev = res.get(0); List<int[]> list = new ArrayList<>(); int i=1; while(i<res.size()){ //overlapping next interval if (prev[0] <= res.get(i)[0] && res.get(i)[0] <= prev[1]){ prev[0] = Math.min(prev[0], res.get(i)[0]); prev[1] = Math.max(prev[1], res.get(i)[1]); i++; } //if not overalapping else { list.add(prev); prev = res.get(i); i++; } } list.add(prev); //final ans int[][] ans = new int[list.size()][2]; int j=0; for(int[] r: list){ ans[j++] = r; } return ans; } } |