Given a collection of intervals, merge all overlapping intervals.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
給予一個區間的集合,合併所有重疊到的區間。
注意: 2019年4月15日更改輸入型別,請重置成預設的程式碼並使用新的方法撰寫。
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
s
是第一個區間的開頭、e
是第一個區間的結尾:
s
和e
之間,就將e
擴大。
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> ans;
sort(intervals.begin(), intervals.end());
bool first = false;
int s, e;
for(int i = 0; i < intervals.size(); i++)
{
if(!first)
{
first = true;
s = intervals[i][0];
e = intervals[i][1];
if(i == intervals.size() - 1)
ans.push_back(vector<int>{s, e});
}
else if(intervals[i][0] <= e)
{
e = max(e, intervals[i][1]);
if(i == intervals.size() - 1)
ans.push_back(vector<int>{s, e});
}
else
{
ans.push_back(vector<int>{s, e});
first = false;
i--;
}
}
return ans;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up