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

    题目链接:https://leetcode-cn.com/problems/merge-intervals/
    题目描述:

    题解:
    排序:
    1.按左边界排序,从左往右遍历,右值越大越好。
    2.按右边界排序,从右往左遍历,左值越小越好。

    class Solution {
    public:
        static bool cmp(vector<int> &a, vector<int> &b)
        {
            return a[0] < b[0];
        }
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            vector<vector<int>> result;
            if(intervals.size() < 2)
                return intervals;
            sort(intervals.begin(), intervals.end(), cmp);  //按左边界排序
            result.push_back(intervals[0]);
            for(int i = 1; i < intervals.size(); i++)
            {
                if(result.back()[1] >= intervals[i][0])
                {
                    result.back()[1] = max(result.back()[1], intervals[i][1]);  //更新边界值
                }else
                {
                    result.push_back(intervals[i]);
                }
            }
            return result;
    
        }
    };
    
    
    
    class Solution {
    public:
        static bool cmp(vector<int> &a, vector<int> &b)  //按右边界排序
        {
            return a[1] < b[1];
        }
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            if(intervals.size() < 2)
                return intervals;
            vector<vector<int>> result;
            sort(intervals.begin(), intervals.end(),cmp);
            result.push_back(intervals[intervals.size() - 1]);
            for(int i = intervals.size() - 2 ; i >= 0; i--)
            {
                if(result.back()[0] <= intervals[i][1])
                {
                    result.back()[0] = min(result.back()[0], intervals[i][0]);
                }else
                    result.push_back(intervals[i]);
            }
            return result;
        }
    };
    
    
  • 相关阅读:
    UML建模之用例图关系
    python模块介绍
    Delphi操作XML(七)
    Delphi操作XML(一)
    Delphi操作XML(五)
    Delphi操作XML(六)
    Delphi操作XML(二)
    Delphi操作XML(四)
    Delphi操作XML(三)
    决心好好写cnblogs
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14968985.html
Copyright © 2011-2022 走看看