runtime 39 ms, beats 94.21% of cpp submissions
nlog(n) solution with explanation

tags: sorting

Merge Intervals

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹้™ฃๅˆ—๏ผŒ้™ฃๅˆ—ๅ…ง็š„ๆฏๅ€‹ๅ…ƒ็ด ้ƒฝๆ˜ฏไธ€ๅ€‹ๅ€้–“ (ๅŒ…ๅซๅ€้–“็š„ไธŠไธ‹้™) ๏ผŒ่ฆๆฑ‚ๆŠŠ้™ฃๅˆ—ๅ…งๆœ‰้‡็–Š็š„ๅ€้–“็ต„ๅˆๆˆๅŒไธ€ๅ€‹ๅ€้–“ใ€‚

ex.
    Input: 
        intervals = [[1,3],[2,6],[8,10],[15,18]]

    Output: 
        [[1,6],[8,10],[15,18]]

    Explanation: 
        Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

๐Ÿง  solution

ๅœจ่€ƒๆ…ฎๅฆ‚ไฝ•่งฃ้กŒไน‹ๅ‰๏ผŒ่ฆๅ…ˆ็†่งฃ่ฆๆ€Ž้บผๅˆคๆ–ทๅ…ฉๅ€‹ๅ€้–“ๆ˜ฏๅฏไปฅๅˆๆˆ็š„

ex.
    [1,3], [2,6] ๆ˜ฏๅ…ฉๅ€‹ๅฏไปฅๅˆๆˆ็š„ๅ€้–“
    ๅ› ็‚บ 2 < 3 ๏ผŒ่กจ็คบไป–ๅ€‘ๆ˜ฏๆœ‰้‡็–Š็š„

    [1,4], [2,3] ไนŸๆ˜ฏๅ…ฉๅ€‹ๅฏไปฅๅˆๆˆ็š„ๅ€้–“
    ่€Œไธ”็ฌฌไธ€ๅ€‹ๅ€้–“ๅฎŒ็พŽๅŒ…ๆ‹ฌไบ†็ฌฌไบŒๅ€‹ๅ€้–“ (่ฉฒๅ€้–“็š„ไธŠ้™่ฆๅ–ๆœ€ๅคงๅ€ผ)

่€ƒๆ…ฎๅฎŒๆ€Ž้บผๅˆๆˆๅ€้–“๏ผŒ้‚„่ฆ่€ƒๆ…ฎๅˆฐ่ผธๅ…ฅ็š„ๅ€้–“ๆ˜ฏๆœช็ถ“ๆŽ’ๅบ็š„๏ผŒไนŸๅฐฑๆ˜ฏๅ…ฉๅ€‹ๅฏ่ƒฝ้‡็–Š็š„ๅ€้–“ไธๆœƒ่ขซๆ”พๅœจ้€ฃ็บŒ็š„ไฝ็ฝฎ๏ผŒๆ‰€ไปฅๆˆ‘ๅ€‘ๅฟ…้ ˆๆŽ’ๅบไธ€ๆฌก่ผธๅ…ฅใ€‚

โณ time complexity

ๆŽ’ๅบ่ผธๅ…ฅ O(nlog(n)) ๏ผŒ้ๆญท่ณ‡ๆ–™ *O(n)*๏ผŒ็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(nlog(n))
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(nlog(n))

๐Ÿ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool cmp(vector<int>& a,vector<int>& b){
if(a[0]==b[0]){
return a[1]<b[1];
}
else{
return a[0]<b[0]; // ๅ›žๅ‚ณไธ‹้™่ผƒไฝŽ็š„ๅ€้–“
}
}
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& inter) {
vector<vector<int>> ans;
sort(inter.begin(),inter.end(),cmp);
for(int i=0;i<inter.size();i++){
if(ans.empty() || ans.back()[1]<inter[i][0]){ // ๅฆ‚ๆžœ็•ถๅ‰้™ฃๅˆ—ๆ˜ฏ็ฉบ็š„ๆˆ–็„กๆณ•ๅˆๆˆ
ans.emplace_back(inter[i]);
}
else{
ans.back()[1] = max(ans.back()[1],inter[i][1]); // ๅฆ‚ๆžœๅฏไปฅๅˆๆˆ๏ผŒๆ›ดๆ–ฐไธŠ้™็‚บ่ผƒๅคง็š„
}
}
return ans;
}
};