057 Insert Interval 插入区间
生活随笔
收集整理的這篇文章主要介紹了
057 Insert Interval 插入区间
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給出一個(gè)無(wú)重疊的按照區(qū)間起始端點(diǎn)排序的區(qū)間列表。
在列表中插入一個(gè)新的區(qū)間,你要確保列表中的區(qū)間仍然有序且不重疊(如果有必要的話,可以合并區(qū)間)。
示例 1:
給定區(qū)間 [1,3],[6,9],插入并合并 [2,5] 得到 [1,5],[6,9].
示例 2:
給定區(qū)間 [1,2],[3,5],[6,7],[8,10],[12,16],插入并合并 [4,9] 得到 [1,2],[3,10],[12,16].
這是因?yàn)樾碌膮^(qū)間 [4,9] 與 [3,5],[6,7],[8,10] 重疊。
詳見(jiàn):https://leetcode.com/problems/insert-interval/description/
Java實(shí)現(xiàn):
/*** Definition for an interval.* public class Interval {* int start;* int end;* Interval() { start = 0; end = 0; }* Interval(int s, int e) { start = s; end = e; }* }*/
class Solution {public List<Interval> insert(List<Interval> intervals, Interval newInterval) {List<Interval> res = new ArrayList<Interval>();for(Interval each: intervals){if(each.end < newInterval.start){res.add(each);}else if(each.start > newInterval.end){res.add(newInterval);newInterval = each; }else if(each.end >= newInterval.start || each.start <= newInterval.end){int nstart = Math.min(each.start, newInterval.start);int nend = Math.max(newInterval.end, each.end);newInterval = new Interval(nstart, nend);}}res.add(newInterval); return res;}
}
參考:https://www.cnblogs.com/springfor/p/3872333.html
轉(zhuǎn)載于:https://www.cnblogs.com/xidian2014/p/8698614.html
總結(jié)
以上是生活随笔為你收集整理的057 Insert Interval 插入区间的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 碧玉多少钱啊?
- 下一篇: Node.js:路由