C++实现LeetCode(56.合并区间)

[LeetCode] 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.

这道和之前那道 Insert Interval 很类似,这次题目要求我们合并区间,之前那题明确了输入区间集是有序的,而这题没有,所以我们首先要做的就是给区间集排序,由于我们要排序的是个结构体,所以我们要定义自己的 comparator,才能用 sort 来排序,我们以 start 的值从小到大来排序,排完序我们就可以开始合并了,首先把第一个区间存入结果中,然后从第二个开始遍历区间集,如果结果中最后一个区间和遍历的当前区间无重叠,直接将当前区间存入结果中,如果有重叠,将结果中最后一个区间的 end 值更新为结果中最后一个区间的 end 和当前 end 值之中的较大值,然后继续遍历区间集,以此类推可以得到最终结果,代码如下:

解法一:

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        if (intervals.empty()) return {};
        sort(intervals.begin(), intervals.end());
        vector<vector<int>> res{intervals[0]};
        for (int i = 1; i < intervals.size(); ++i) {
            if (res.back()[1] < intervals[i][0]) {
                res.push_back(intervals[i]);
            } else {
                res.back()[1] = max(res.back()[1], intervals[i][1]);
            }
        }
        return res;
    }
};

下面这种解法将起始位置和结束位置分别存到了两个不同的数组 starts 和 ends 中,然后分别进行排序,之后用两个指针i和j,初始化时分别指向 starts 和 ends 数组的首位置,然后如果i指向 starts 数组中的最后一个位置,或者当 starts 数组上 i+1 位置上的数字大于 ends 数组的i位置上的数时,此时说明区间已经不连续了,我们来看题目中的例子,排序后的 starts 和 ends 为:

starts:    1    2    8    15

ends:     3    6    10    18

红色为i的位置,蓝色为j的位置,那么此时 starts[i+1] 为8,ends[i] 为6,8大于6,所以此时不连续了,将区间 [starts[j], ends[i]],即 [1, 6] 加入结果 res 中,然后j赋值为 i+1 继续循环,参见代码如下:

解法二:

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        int n = intervals.size();
        vector<vector<int>> res;
        vector<int> starts, ends;
        for (int i = 0; i < n; ++i) {
            starts.push_back(intervals[i][0]);
            ends.push_back(intervals[i][1]);
        }
        sort(starts.begin(), starts.end());
        sort(ends.begin(), ends.end());
        for (int i = 0, j = 0; i < n; ++i) {
            if (i == n - 1 || starts[i + 1] > ends[i]) {
                res.push_back({starts[j], ends[i]});
                j = i + 1;
            }
        }
        return res;
    }
};

这道题还有另一种解法,这个解法直接调用了之前那道题 Insert Interval 的函数,由于插入的过程中也有合并的操作,所以我们可以建立一个空的集合,然后把区间集的每一个区间当做一个新的区间插入结果中,也可以得到合并后的结果,那道题中的四种解法都可以在这里使用,但是没必要都列出来,这里只选了那道题中的解法二放到这里,代码如下:

解法三:

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> res;
        for (int i = 0; i < intervals.size(); ++i) {
            res = insert(res, intervals[i]);
        }
        return res;
    }
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int> newInterval) {
        vector<vector<int>> res;
        int n = intervals.size(), cur = 0;
        for (int i = 0; i < n; ++i) {
            if (intervals[i][1] < newInterval[0]) {
                res.push_back(intervals[i]);
                ++cur;
            } else if (intervals[i][0] > newInterval[1]) {
                res.push_back(intervals[i]);
            } else {
                newInterval[0] = min(newInterval[0], intervals[i][0]);
                newInterval[1] = max(newInterval[1], intervals[i][1]);
            }
        }
        res.insert(res.begin() + cur, newInterval);
        return res;
    }
};

到此这篇关于C++实现LeetCode(56.合并区间)的文章就介绍到这了,更多相关C++实现合并区间内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(57.插入区间)

    [LeetCode] 57. Insert Interval 插入区间 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Input: int

  • C++实现LeetCode(49.群组错位词)

    [LeetCode] 49. Group Anagrams 群组错位词 Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat",&quo

  • C++实现LeetCode(50.求x的n次方)

    [LeetCode] 50. Pow(x, n) 求x的n次方 Implement pow(x, n), which calculates x raised to the power n(xn). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation

  • C++实现LeetCode(53.最大子数组)

    [LeetCode] 53. Maximum Subarray 最大子数组 Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1]

  • C++实现LeetCode(52.N皇后问题之二)

    [LeetCode] 52. N-Queens II N皇后问题之二 The n-queens puzzle is the problem of placing nqueens on an n×n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example: Inpu

  • C++实现LeetCode(60.序列排序)

    [LeetCode] 60. Permutation Sequence 序列排序 The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" &

  • C++实现LeetCode(48.旋转图像)

    [LeetCode] 48. Rotate Image 旋转图像 You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allo

  • C++实现LeetCode(56.合并区间)

    [LeetCode] 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

  • C语言题解Leetcode56合并区间实例

    目录 解题思路 解题遇到的问题 后续需要总结学习的知识点 解题思路 题目链接 56. 合并区间 本质在于两两做对比,如果两个区间,可以合并,则为结果二维数组中的一员,如果不可合并,则放入结果二维数组,所以根本在于,如何判断两个区间,是可合并,还是不可合并 1.首先将二维数组,按照左端元素进行排序 2.将第一个元素放入结果区间列表 3.如果当前区间的左端元素比结果区间列表最后一个区间右端元素小,则存在包含关系,此时只需更新右端元素即可 (更新为当前区间的右端元素与结果区间的右端元素的最大值) 4.

  • C++实现LeetCode(23.合并k个有序链表)

    [LeetCode] 23. Merge k Sorted Lists 合并k个有序链表 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 这

  • C++实现LeetCode(228.总结区间)

    [LeetCode] 228.Summary Ranges 总结区间 Given a sorted integer array without duplicates, return the summary of its ranges. Example 1: Input:  [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous ran

  • C++实现LeetCode(163.缺失区间)

    [LeetCode] 163. Missing Ranges 缺失区间 Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Example: Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99, Output: ["2&q

  • Java如何将若干时间区间进行合并的方法步骤

    问题原因 工作中突然有个场景,需要合并时间区间.将若干闭合时间区间合并,实现思路如下: 1. 先对日期区间进行按时间顺序排序,这样后一个区间(记为next)的from一定是不小于前一个(记为prev)from的. 2.在进行循环比较的时候,对于next区间,假设next.from大于prev.to就说明这两个区间是分开的,要新增区间.否则说明next.from在[prev.from, prev.to]内,这时要看next.to是否是大于prev.to,如果大于就要合并区间. 具体实现 publi

  • python实现二分类的卡方分箱示例

    解决的问题: 1.实现了二分类的卡方分箱: 2.实现了最大分组限定停止条件,和最小阈值限定停止条件: 问题,还不太清楚,后续补充. 1.自由度k,如何来确定,卡方阈值的自由度为 分箱数-1,显著性水平可以取10%,5%或1% 算法扩展: 1.卡方分箱除了用阈值来做约束条件,还可以进一步的加入分箱数约束,以及最小箱占比,坏人率约束等. 2.需要实现更多分类的卡方分箱算法: 具体代码如下: # -*- coding: utf-8 -*- """ Created on Wed No

  • C语言合并排序及实例代码

    归并排序也称合并排序,其算法思想是将待排序序列分为两部分,依次对分得的两个部分再次使用归并排序,之后再对其进行合并.仅从算法思想上了解归并排序会觉得很抽象,接下来就以对序列A[0], A[l]-, A[n-1]进行升序排列来进行讲解,在此采用自顶向下的实现方法. 操作步骤如下: (1)将所要进行的排序序列分为左右两个部分,如果要进行排序的序列的起始元素下标为first,最后一个元素的下标为last,那么左右两部分之间的临界点下标mid=(first+last)/2,这两部分分别是A[first

  • Queryable.Union 方法实现json格式的字符串合并的具体实例

    1.在数据库中以json字符串格式保存,如:[{"name":"张三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":&qu

随机推荐