并查集系列(三)——继承者问题

本文介绍如何使用并查集数据结构实现一个数据类型,该数据类型能够在对数时间内完成从集合S中移除元素及查找移除元素后的继任者操作。继任者定义为集合S中大于等于被移除元素的最小值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

  Given a set of N integers S={0,1,…,N−1} and a sequence of requests of the following form:
  
1. Remove x from S
2. Find the successor of x: the smallest y in S such that y≥x.
3. design a data type so that all operations (except construction) should take logarithmic time or better.

##思路分析
  首先来看题目要求是对数时间,这样的话肯定不可能遍历完整个数组(这样至少为n),加之这一部分学的是并查集。。所以思考怎么使用并查集来解决这个问题。这个问题思考了很久啊。。一直没有答案,这里不得不吐槽一下国内写的博客。。完全是为自己写的,应该只有作者本人可以看懂。。。不扯了,接下来借鉴了墙外的一些思路来写的。
  当确定这个题可能要使用并查集的时候我们再来仔细分析一下要求,首先给定的是一段连续的自然数序列(或者数组下标);第二点我们要获取移除的successor: 剩余数中大于数的队列中的最小数。我们来举个例子,
  {1 …8}在这八个数中我们移除6,6的successor为7(find(6) ==7);
  再移除5,find(5) == 7;
  再移除2 , find(2) == 3 find(3) = 3 find(5) ==7 
  我们可以看到输出的值为一个连通域中最大值+1,而这个连通域由我们remove()的数组成。这就想起了上一道题,我们使用并查集来实现在对数时间中查找列表中的最大项。

代码

public class Successor {
    private int n;
    private boolean[] isRemove;
    private FindMax findMax;

    public Successor(int n){
        this.n = n; //大小为n的列表
        findMax = new FindMax();    //上一部分的FindMax类,提供union和find方法
        isRemove = new boolean[n];  //判断列表项中对应位置的数是否被移除
        for (int i = 0; i < isRemove.length; i++) {
            isRemove[i] = false;
        }
    }

    public void remove(int x) {
        isRemove[x] = true;
        if (x>0 && isRemove[x-1]){
            findMax.union(x,x-1);
        }else if (x<n-1 && isRemove[x+1]){
            findMax.union(x,x+1);
        }
    }

    public int getSuccessor(int x) {
        if(x<0 || x>n-1){   //输入不合法
            return -1;
        }else if(isRemove[x]){     //若是已经被移除的项,输出移除项中最大项+1
                return findMax.find(x)+1;
        }else {     //若不是移除项,则按照规则输出自己
            return x;
        }
    }

    public static void main(String[] args) {
        Successor successor = new Successor(8);
        successor.remove(3);
        successor.remove(2);
        successor.remove(0);
        successor.remove(4);
        successor.remove(7);
        System.out.println("the successor is : " + successor.getSuccessor(2));
    }
}

输出:

the successor is : 5

参考文章

http://vancexu.github.io/2015/07/21/intro-to-union-find-data-structure-exercise.html(墙内)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值