lintcode-156-合並區間


156-合並區間

給出若干閉合區間,合並所有重疊的部分。

樣例

給出的區間列表 => 合並后的區間列表:
[ [
[1, 3], [1, 6],
[2, 6], => [8, 10],
[8, 10], [15, 18]
[15, 18] ]
]

挑戰

O(n log n) 的時間和 O(1) 的額外空間。

標簽

排序 數組 領英 谷歌

思路

由於題目沒有明確說明輸入集是有序的,所以首先對輸入集排序(自定義比較函數,以 start 為基准),之后開始合並:

  1. 首先把第一個區間存入結果中
  2. 然后從第二個開始遍歷區間集:
    • 如果結果中最后一個區間和遍歷的當前區間無重疊,直接將當前區間存入結果中
    • 如果有重疊,將結果中最后一個區間的end值更新為結果中最后一個區間的end和當前end值之中的較大值

code

/**
 * Definition of Interval:
 * class Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * };
 */
class Solution {
public:
    static bool cmp(const Interval &a, const Interval &b) {
        return a.start < b.start;
    }
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    vector<Interval> merge(vector<Interval> &intervals) {
        // write your code here
        int size = intervals.size();
        if (size <= 0) {
            return vector<Interval>();
        }

        vector<Interval> result;
        sort(intervals.begin(), intervals.end(), cmp);
        result.push_back(intervals[0]);
        for (int i = 1; i < size; i++) {
            if (result.back().end >= intervals[i].start) {
                result.back().end = (result.back().end > intervals[i].end) ? result.back().end : intervals[i].end;
            }
            else {
                result.push_back(intervals[i]);
            }
        }
        return result;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM