LeetCode刷题笔记--56. Merge Intervals

56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

这道题的解题思路是,先sort从小到大排列一下(按照[x,y]的x排列)。这第一步也是试出来的,本来以为给的数组是排好的,提交后才发现,有的case是顺序打乱的。

例如:

Sorting Example

排好顺序以后,我们假设有个区间最小值和最大值。最小值就是第一个括号内左边的值了,最大值初始为第一个括号内右边的值。然后往后逐个判断括号内右边的值是否<=max,如果是,则往右移动,最后记录一个最大的值。得到第一个区间,写到ans中,继续往后历,直到<size()。

AC的答案(C++):

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> ans;
        ans.clear();
        if(intervals.size()==0)return ans;
        vector<int> t;
        t.clear();
        sort(intervals.begin(),intervals.end());
        
        for(int i=0;i<intervals.size();i++)
        {
            int x=i;
            int y=i+1;
            int m=intervals[x][1];
            while((y<=intervals.size()-1)&&intervals[y][0]<=m)
            {
                m=max(m,intervals[y][1]);
                y++;
            }
            t.clear();
            t.push_back(intervals[x][0]);
            t.push_back(m);
            ans.push_back(t);
            i=y-1;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/89554999