LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結:Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,

Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. 

這道題的要求是將給定的一組間隔中有重疊的進行合并。

將間隔合并,首先要找到相鄰的間隔,然後看其是否有重疊,如果有,就進行合并。

因此,首先考慮對數組排序。排序的時候,只需要按照間隔的起始時間排序即可。然後遍曆數組,當前一個間隔的結束時間不小於當前間隔的開始時間,說明有重疊,需要進行合并。合并的時候,新的間隔的結束時間等於這兩個間隔結束時間的最大值。

實現過程中,先將第一個間隔放到新數組中,然後從第二個開始往後遍曆,如果有重疊,就改變新數組中最後元素的結束時間;如果沒有重疊,就添加到新數組中即可。

時間複雜度:O(nlogn)

空間複雜度:O(n)

 1 bool cmp(Interval i1, Interval i2) 2 { 3     return i1.start < i2.start; 4 } 5  6 class Solution 7 { 8 public: 9     vector<Interval> merge(vector<Interval> &intervals)10     {11         vector<Interval> vi;12 13         if(intervals.size() == 0)14             return vi;15 16         sort(intervals.begin(), intervals.end(), cmp);17 18         vi.push_back(intervals[0]);19         for(int i = 1; i < intervals.size(); ++ i)20         {21             if(vi[vi.size() - 1].end >= intervals[i].start)22                 vi[vi.size() - 1].end = max(vi[vi.size() - 1].end, intervals[i].end);23             else24                 vi.push_back(intervals[i]);25         }26         return vi;27     }28 };

轉載請說明出處:LeetCode --- 56. Merge Intervals

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.