区间合并讲解

简介: 区间合并讲解

y总模板:


// 将所有存在交集的区间合并
void merge(vector<PII> &segs)
{
vector<PII> res;
sort(segs.begin(), segs.end());
int st = -2e9, ed = -2e9;
for (auto seg : segs)
if (ed < seg.first)
{
if (st != -2e9) res.push_back({st, ed});
st = seg.first, ed = seg.second;
}
else ed = max(ed, seg.second);
if (st != -2e9) res.push_back({st, ed});
segs = res;
}


https://www.acwing.com/problem/content/805/

思路:

1.将每个区间左端点排序

2.如果下一个区间左端点大于老区间右端点,则找到了新区间,数量+1,添加新区间

否则更新较大的右端点


public static void main(String[] args) throws IOException {
        Scanner sc=new Scanner(System.in);
        int n= sc.nextInt();
        ArrayList<int []> list=new ArrayList<>();
        while (n-->0){
            int []a=new int [2];
            a[0]=sc.nextInt();
            a[1]=sc.nextInt();
            list.add(a);
        }
        System.out.println(merge(list));
    }
    public static int merge(ArrayList <int []> list){
        ArrayList <int []> newlist=new ArrayList<>();
        //对每个区间的左区间点进行升序排列
        list.sort(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        int l=Integer.MIN_VALUE,r=Integer.MIN_VALUE;
        for (int[] a : list) {
            //如果新的左区间大于旧的右区间
            if(a[0]>r){
                //那么意味着这是一个新区间,与原来区间不一样
                if(l!=Integer.MIN_VALUE) {
                    newlist.add(new int[]{l, r});
                }
                l=a[0];
                r=a[1];
            }else{
                r=Math.max(r,a[1]);
            }
        }
        if(l!=Integer.MIN_VALUE)  newlist.add(new int[]{l,r});
        list.clear();
        for (int[] b : newlist) {
            list.add(b);
        }
        return list.size();
    }
相关文章
|
9月前
|
C++
线段树的区间修改
线段树的区间修改
30 0
|
3月前
|
索引 NoSQL 容器
树状数组与线段树
树状数组与线段树
|
11月前
|
算法
数星星(树状数组模板题)
数星星(树状数组模板题)
38 0
|
人工智能 BI
1236:区间合并 2020-12-27
1236:区间合并 2020-12-27
|
人工智能 索引
树状数组总结
能够解决数据压缩里的累积频率的计算问题,现多用于高效计算数列的前缀和、区间和。
111 0
树状数组总结
|
机器学习/深度学习 存储 算法
区间合并算法
区间合并算法