#pragma warning(disable:4996) #include <Windows.h> #include <tchar.h> #include <cstdio> #include <vector> using namespace std; /* submit time : 1 request : 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: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. */ struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> res; int length = intervals.size(), newStart = newInterval.start; int i = 0; while (i < length && intervals[i].start <= newStart) res.push_back(intervals[i++]); // insert newInterval int size = res.size(); if (size == 0) { i = 0; res.push_back(newInterval); } else { if (res[size - 1].end >= newInterval.start) res[size - 1].end = max(res[size - 1].end, newInterval.end); else res.push_back(newInterval); } // insert the left while (i < length) { size = res.size(); if (res[size - 1].end >= intervals[i].start) { res[size - 1].end = max(res[size - 1].end, intervals[i].end); ++i; } else res.push_back(intervals[i++]); } return res; }
LeetCode_56insert [Insert Interval]
时间: 2024-10-05 06:51:52