【leetcode】56. Merge Intervals

@requires_authorization 
@create_time 2015.7.10 11:07
@author johnsondu
@url https://leetcode.com/problems/merge-intervals/
/** * 进行数组排序,然后按照贪心策略进行合并,具体是考察 * 下一个元素的start是否是介于当前的start和end之间, * 如果是,则根据需要更新当前end。 * 时间复杂度(O(nlogn))-->排序, 结果获取O(n) * 空间复杂度(O(n)) */

/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */
class Solution {
public:
    static bool cmp(const Interval &a, const Interval &b){
        if(a.start == b.start) return a.end < b.end;
        return a.start < b.start;
    }

    vector<Interval> merge(vector<Interval>& intervals) {
        int len = intervals.size();
        sort(intervals.begin(), intervals.end(), cmp);

        vector<Interval> ans;
        for(int i = 0; i < len; i ++){
            int st = intervals[i].start;
            int ed = intervals[i].end;
            int idx = i + 1;
            while(idx < len){
                if(intervals[idx].start >= st && intervals[idx].start <= ed){
                    if(intervals[idx].end > ed) ed = intervals[idx].end;
                    idx ++;
                }
                else break;
            }
            Interval tmp(st, ed);
            ans.push_back(tmp);
            i = idx - 1;
        }

        return ans;
    }
};

你可能感兴趣的:(LeetCode,merge,algorithms)