zoukankan      html  css  js  c++  java
  • LeetCode 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].

    题意:去掉反复的区间。

    思路:排序后,再比較end的情况。

    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
     bool cmp(const Interval &a, const Interval &b) {
        return a.start < b.start;
     }
    
    class Solution {
    public:
        vector<Interval> merge(vector<Interval> &intervals) {
            int n = intervals.size();
    
            vector<Interval> ans;
            sort(intervals.begin(), intervals.end(), cmp);
            for (int i = 0; i < intervals.size(); i++) {
                if (ans.size() == 0) ans.push_back(intervals[i]);
                else {
                    int m = ans.size();
                    if (ans[m-1].start <= intervals[i].start && ans[m-1].end >= intervals[i].start) 
                        ans[m-1].end = max(ans[m-1].end, intervals[i].end);
                    else ans.push_back(intervals[i]);
                }
            }
    
            return ans;
        }
    };



  • 相关阅读:
    第三周助教总结
    第三周作业
    第二周助教总结
    参数和指针
    第二周作业
    第一周作业 2
    第一周作业 1
    第七周助教小结
    第六周助教小结
    第五周助教总结
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5142677.html
Copyright © 2011-2022 走看看