leetcode : Insert Interval
runtime 13 ms, beats 95.58% of cpp submissions
O(n) solution with explanation
tags: None
๐ link
๐ 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 | class Solution { |