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;
}

 

转载于:https://www.cnblogs.com/250101249-sxy/p/10422535.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值