博客
关于我
LeetCode 57. Insert Interval
阅读量:119 次
发布时间:2019-02-26

本文共 2026 字,大约阅读时间需要 6 分钟。

一 题目

  

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]Output: [[1,2],[3,10],[12,16]]Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

二 分析

   hard 级别,题目让我们在一系列非重叠的区间中插入一个新的区间。上个区间的题目:  是合并。这个还要复杂些,因为单纯的没有重合的区域,遍历原来的区间位置,在对应位置直接插入就行,重合的不行,重合的区域遇到多个重合的情况,可能要更新为一个新的区间范围,包含原来的区间,再把新的区间加入到结果集。

     具体实现思路就是循环并合并,for循环现有区间,判断与新插入的Interval 是否重合

  • 在newInterval start前end的
  • 在newInterval end后start的

。不重合直接加入到结果集。重合的取新的区间范围,min,max 分别取最小与最大值。在接着判断下一个元素是否可以合并。

public static void main(String[] args) {		int[][] intervals ={				{1,2},{3,5},{6,7},{8,10},{12,16}		};		int[] newInterval = {4,8};		int[][] res =insert(intervals,newInterval);		System.out.println( JSON.toJSON(res));	}		public static int[][] insert(int[][] intervals, int[] newInterval) {		List
res = new ArrayList
(); for(int i=0;i
newInterval[1]){ res.add(intervals[i] ); } else{//重叠,进行合并更新interval newInterval[0] = Math.min(newInterval[0] ,intervals[i][0]); newInterval[1] = Math.max(newInterval[1], intervals[i][1]); } }//加入最后一个区间 res.add(newInterval); int[][] temp = res.toArray(new int[0][0]); Arrays.sort(temp, new Comparator
(){ @Override public int compare(int[] o1, int[] o2) { // TODO Auto-generated method stub return Integer.compare(o1[0],o2[0]); } }); return temp; }

Runtime: 2 ms, faster than 39.71% of Java online submissions for Insert Interval.

Memory Usage: 41.6 MB, less than 71.88% of Java online submissions for Insert Interval.

最后加了排序,输出可能是乱序的。

因为加了排序,所以时间复杂度O(NlogN). 有时间再看看网上大神是怎么做的。

 

转载地址:http://irdy.baihongyu.com/

你可能感兴趣的文章
localhost:5000在MacOS V12(蒙特利)中不可用
查看>>
logstash mysql 准实时同步到 elasticsearch
查看>>
Luogu2973:[USACO10HOL]赶小猪
查看>>
mabatis 中出现< 以及> 代表什么意思?
查看>>
Mac book pro打开docker出现The data couldn’t be read because it is missing
查看>>
MAC M1大数据0-1成神篇-25 hadoop高可用搭建
查看>>
mac mysql 进程_Mac平台下启动MySQL到完全终止MySQL----终端八步走
查看>>
Mac OS 12.0.1 如何安装柯美287打印机驱动,刷卡打印
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MariaDB的简单使用
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>