zoukankan      html  css  js  c++  java
  • leetcode-合并区间

    Python解法:

    def merge(intervals):
        intervals = sorted(intervals)
        res = []
        n = len(intervals)
        i = 0
        while i < n:
            left = intervals[i][0]
            right = intervals[i][1]
            while i < n-1 and intervals[i+1][0] <= right:
                i += 1
                right = max(intervals[i][1], right)
            res.append([left, right])
            i += 1
        return res
    
    
    print(merge([[1,2],[3,8],[6,4],[15,18]]))

    C++解法:

    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            vector<vector<int>> res;
            if(intervals.size() == 0)
                return res;
            sort(intervals.begin(), intervals.end());
            
            int i = 0;
            vector<int> temp {0, 0};
            while(i < intervals.size()){
                int left = intervals[i][0];
                int right = intervals[i][1];
                
                while(i < intervals.size() - 1 && right >= intervals[i+1][0]){
                    ++i;
                    right = max(right, intervals[i][1]);
                }
                ++i;
                temp[0] = left;
                temp[1] = right;
                res.push_back(temp);
            }
            
            return res;
        }
        
        bool compare(vector<int>& a, vector<int>&b){
            return a[0] < b[0];
        }
    };
    Try to be a giver
  • 相关阅读:
    单调队列+二分 G
    dp cf 1700 最近几天的刷题
    dp 20190618
    dp 20190617
    dp cf 20190615
    dp cf 20190614
    powercli
    zabbix docker-weixin
    cenetos-大文件排序
    esxcli命令
  • 原文地址:https://www.cnblogs.com/HannahGreen/p/12103376.html
Copyright © 2011-2022 走看看