leetcode : Merge Intervals
runtime 39 ms, beats 94.21% of cpp submissions
nlog(n) solution with explanation
tags: sorting
๐ link
๐ 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 | bool cmp(vector<int>& a,vector<int>& b){ |