leetcode(57)插入区间
插入区间
解题思路:二分查找+区间前合并+区间后合并
class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { int len = intervals.length; if(len==0){ return new int[][]{{newInterval[0],newInterval[1]}}; } List<int[]> result = new ArrayList<>(); int start = 0; int end = len - 1; int mid = 0; while(start<=end){ mid = (start+end)/2; if(intervals[mid][0]<newInterval[0]){ start = mid + 1; }else{ end = mid - 1; } }
//直接复制,不需要合并 for(int i=0;i<end;++i){ result.add(intervals[i]); }
//区间前合并 if(end>=0){ if(intervals[end][1]>=newInterval[0]){ newInterval[0] = intervals[end][0]; newInterval[1] = Math.max(intervals[end][1],newInterval[1]); }else{ result.add(intervals[end]); } }
//区间后合并 int i = 0; for(i=start;i<len;++i){ if(intervals[i][0]<=newInterval[1]){ newInterval[1] = Math.max(newInterval[1],intervals[i][1]); }else{ result.add(newInterval); for(int j=i;j<len;++j){ result.add(intervals[j]); } break; } } if(i==len){ result.add(newInterval); } int[][] res = new int[result.size()][2]; return result.toArray(res); } }