Directory link:
Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog
GitHub synchronization problem solving project:
https://github.com/September26/java-algorithms
Original title link: LeetCode official website - the technology growth platform loved by geeks around the world
describe:
Use an array intervals
to represent a set of several intervals, where a single interval is intervals[i] = [starti, endi]
. Please merge all overlapping intervals and return an array of non-overlapping intervals that exactly covers all intervals in the input .
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: The intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: The intervals [1,4] and [4,5] can be considered as overlapping intervals.
hint:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
Problem-solving ideas:
* Problem-solving ideas:
* First sort according to the size of intervals[i].left, and then select the first one as the header. Compare the header with the following ones one by one, divided into three situations:
* 1.header.right<interval.left; At this time, it means that the two intervals do not intersect, then add header to out, and update interval to header;
* 2.header.right>=interval.right; At this time, it means that the header completely covers the interval, so it can be skipped directly;
* 3.header.right<interval.right; At this time, it means that the two intervals intersect and cannot completely cover each other. Then the right of the header is updated, which is equal to the merge of the intervals.
Code:
class Solution56
{
public:
vector<vector<int>> merge(vector<vector<int>> intervals)
{
sort(intervals.begin(), intervals.end(), [](vector<int> v1, vector<int> v2)
{ return v1[0] - v2[0] < 0; });
vector<vector<int>> out;
vector<int> header;
for (vector<int> interval : intervals)
{
if (header.size() == 0)
{
header = interval;
continue;
}
if ((header)[1] < interval[0])
{
out.push_back(header);
header = interval;
continue;
}
if ((header)[1] >= interval[1])
{
continue;
}
header[1] = interval[1];
}
out.push_back(header);
return out;
}
};