runtime 13 ms, beats 95.58% of cpp submissions
O(n) solution with explanation

tags: None

Insert Interval

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹ sorted ๅ€้–“้™ฃๅˆ— intervals๏ผŒไปฅๅŠไธ€ๅ€‹้œ€่ฆๆ–ฐๅขž็š„ๅ€้–“ newInterval๏ผŒ่ซ‹ๆฑ‚ๅฐ‡ๅ€้–“ๆ”พ้€ฒ intervals ๏ผŒไธฆไฟๆŒ intervals ไป็„ถๆ˜ฏๅทฒๆŽ’ๅบ็š„ใ€‚

ex.
    Input: 
        intervals = [[1,3],[6,9]], newInterval = [2,5]
    Output: 
        [[1,5],[6,9]]

    ๆณจๆ„ๅฏ่ƒฝๆœƒๅ‡บ็พ้œ€่ฆๅˆไฝตๅ€้–“็š„ๆƒ…ๅฝข

๐Ÿง  solution

็•ถ็œ‹่ฆ‹็ตฆๅฎš็š„่ผธๅ…ฅๆ˜ฏไธ€ๅ€‹ sorted array ๏ผŒๅฏ่ƒฝๆœƒๅพˆ็›ด่ฆบ็š„่ช็‚บๆœฌ้กŒ้œ€่ฆไฝฟ็”จ binary search ๏ผŒไฝ†็”ฑๆ–ผ้œ€่ฆๆ–ฐๅขž่ณ‡ๆ–™ๅˆฐ้™ฃๅˆ—ไธญ๏ผŒๅ› ๆญคๆœ€ๅทฎๆ™‚้–“่ค‡้›œๅบฆไธ€ๅฎšๆœƒ่ขซ้™ๅˆถๅœจ O(n) ๏ผŒๆ‰€ไปฅไฝฟ็”จ linear search ๅ่€Œ่ƒฝ้ฟๅ…ๅœจๆœๅฐ‹ๆ™‚ๅ‡บ็พ็š„ไธ€ไบ›่™•็†ๅ•้กŒใ€‚

ๅœจๅš linear search ๆ™‚๏ผŒๆ–ฐๅ€้–“็›ธๅฐๆ–ผ็•ถๅ‰ๅ€้–“ๅ…ฑๆœ‰ 3 ็จฎๆƒ…ๅฝขใ€‚

  • ๅ€้–“ n ๅœจ็•ถๅ‰ๅ€้–“็š„ ๅ‰ ๆ–น๏ผŒ่ค‡่ฃฝ็•ถๅ‰ๅ€้–“
  • ๅ€้–“ n ๅœจ็•ถๅ‰ๅ€้–“็š„ ๅพŒ ๆ–น๏ผŒ่ค‡่ฃฝๅ€้–“ n ๏ผŒไธฆๅœจๅพŒๆ–น่ค‡่ฃฝๅ‰ฉไธ‹็š„ๅ€้–“๏ผŒๅ›žๅ‚ณ
  • ๅ€้–“ n ่ˆ‡็•ถๅ‰ๅ€้–“ๆœ‰้‡็–Š๏ผŒๅฐ‡ n ็š„ไธŠไธ‹้™ๆ›ดๆ–ฐ (็ถญ่ญท้‡็–Š็š„ๆœ€ๅคงๅ€้–“)

่€Œๅฆ‚ๆžœๆฒ’ๆœ‰ไฝ็ฝฎๆŠŠ n ๆ–ฐๅขž้€ฒ้™ฃๅˆ—ไธญ๏ผŒไปฃ่กจ n ๆ‡‰่ฉฒๆ”พๅœจๆœ€ๅพŒ

โณ time complexity

้ๆญทไธ€ๆฌก้™ฃๅˆ—๏ผŒๆ™‚้–“่ค‡้›œๅบฆ O(n)
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(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
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& in, vector<int>& n) {
vector<vector<int>> ans;
for(int i=0;i<in.size();i++){
if(in[i][1]<n[0]){ // ๅฆ‚ๆžœๅ€้–“ n ๅœจ็•ถๅ‰ๅ€้–“็š„ๅพŒๆ–น
ans.emplace_back(in[i]);
}
else if(n[1]<in[i][0]){ // ๅฆ‚ๆžœ้œ€่ฆๆ–ฐๅขž็š„ๅ€้–“ๅœจ็•ถๅ‰ๅ€้–“็š„ๅ‰ๆ–น
// ๅ‰‡ๅพŒๆ–นๅ€้–“ๅฏ็›ดๆŽฅ่ค‡่ฃฝไธฆๅ›žๅ‚ณ
ans.emplace_back(n);
ans.insert(ans.end(),in.begin()+i,in.end());
return ans;
}
else{ // ๅ‡บ็พ้œ€่ฆๅˆไฝตๅ€้–“็š„ๆƒ…ๆณ
// ่ฎ“ๅ€้–“ n ็ถญๆŒ่ขซๅˆไฝต็š„ไธ‹้™ๅŠไธŠ้™
n[0] = min(n[0],in[i][0]);
n[1] = max(n[1],in[i][1]);
}
}
ans.emplace_back(n); // ๅ€้–“ๅ‡บ็พๅœจ็ตๅฐพ
return ans;
}
};