Leetcode(java) 57. Insert Interval

Q:

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.

A:

There are three cases:

1. newInterval is completely smaller than the current interval:

        add the newInternal in the list and add the remaining intervals to list directly

2. newInterval overlaps the current interval:

        merge this two intervals considering left boundary and right boundary and then compare this merged interval with remaining intervals.

3. newInterval is completely larger than the current interval:

        add the current interval to the list.

Code:

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        if(intervals.length==0){
            int[][] res = new int[1][2];
            res[0] = newInterval;
            return res;
        }
        List<int[]> list = new ArrayList<int[]>();    
        for(int i = 0;i<intervals.length;i++){
            if(newInterval[1]<intervals[i][0]){
                list.add(newInterval);
                while(i<intervals.length){
                    list.add(intervals[i++]);
                }
                return list.toArray(new int[list.size()][2]);
            }else if(newInterval[0]<=intervals[i][1]){
                intervals[i][1] = Math.max(intervals[i][1],newInterval[1]);
                intervals[i][0] = Math.min(intervals[i][0],newInterval[0]);
                int j = i+1;
                while(j<intervals.length){
                    if(intervals[j][0]<=intervals[i][1]){
                        intervals[i][1] = Math.max(intervals[i][1],intervals[j][1]);
                        j++;
                    }else{
                        break;
                    }
                }
                list.add(intervals[i]);
                while(j<intervals.length){
                    list.add(intervals[j++]);
                }
                return list.toArray(new int[list.size()][2]);
            }else{
                list.add(intervals[i]);
            }
        }
        list.add(newInterval);
        return list.toArray(new int[list.size()][2]);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值