zoukankan      html  css  js  c++  java
  • 56[LeetCode] .Merge Intervals


    Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note:

    The solution set must not contain duplicate quadruplets.

    Example:

    Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
    
    A solution set is:
    [
      [-1,  0, 0, 1],
      [-2, -1, 1, 2],
      [-2,  0, 0, 2]
    ]



    
    
    
    

    注意sort() 中的cmp()比较函数的定义要放在类外面:

    /**
     * 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(Interval a,Interval b){return a.start<b.start;}
    class Solution { public: vector<Interval> merge(vector<Interval>& ins) { if (ins.empty()) return vector<Interval>{}; vector<Interval> res; sort(ins.begin(), ins.end(), cmp); res.push_back(ins[0]); for (int i = 1; i < ins.size(); i++) { if (res.back().end < ins[i].start) res.push_back(ins[i]); else res.back().end = max(res.back().end, ins[i].end); } return res; } };

    如在在sort中定义排序方法应该这么写:

    vector<Interval> merge(vector<Interval>& ins) {
        if (ins.empty()) return vector<Interval>{};
        vector<Interval> res;
        sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});
        res.push_back(ins[0]);
        for (int i = 1; i < ins.size(); i++) {
            if (res.back().end < ins[i].start) res.push_back(ins[i]);
            else
                res.back().end = max(res.back().end, ins[i].end);
        }
        return res;
    }
  • 相关阅读:
    获取请求IP
    Excel导入工具类兼容xls和xlsx
    Openshift 4.3环境的离线Operatorhub安装
    RHEL学习
    OpenShift Service Mesh 培训作业
    OpenId Connect认证配置
    Route Sharding in OpenShift 4.3
    OpenShift 4.3环境中创建基于Go的Operator
    Quay和Clair的集成
    Quay 基础版安装和部署
  • 原文地址:https://www.cnblogs.com/250101249-sxy/p/10422535.html
Copyright © 2011-2022 走看看