每天刷个算法题20160522:支持各种类型的并查集

博主分享了自己坚持每天刷算法题的心得,并创建了一个开源项目,包含每日算法题目的代码实现,其中重点介绍了自研的、支持任意类型的并查集算法,强调代码原创且可能不易理解,未来计划涉及更多如DP、贪心等算法类型。
摘要由CSDN通过智能技术生成

版权所有。所有权利保留。

欢迎转载,转载时请注明出处:

http://blog.csdn.net/xiaofei_it/article/details/51524671


为了防止思维僵化,每天刷个算法题。已经刷了几天了,现在发点代码。

我已经建了一个开源项目,每天的题目都在里面:

https://github.com/Xiaofei-it/Algorithms

绝大部分算法都是我自己写的,没有参考网上通用代码。读者可能会觉得有的代码晦涩难懂,因为那是我自己的理解。

最近几天都是在写一些原来的东西,大多数是非递归。以后准备刷点DP、贪心之类的题。

下面是支持任意类型的并查集:

/**
 *
 * Copyright 2016 Xiaofei
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package xiaofei.algorithm;

import java.util.HashMap;

/**
 * Created by Xiaofei on 16/5/22.
 */
public class DisjointSet<T> {
    private HashMap<T, Node<T>> map = new HashMap<>();

    public DisjointSet() {

    }

    public void makeSet(T data) {
        if (map.containsKey(data)) {
            return;
        }
        map.put(data, new Node<T>(data));
    }

    private Node<T> findInternal(Node<T> node) {
        if (node.parent != node) {
            node.parent = findInternal(node.parent);
        }
        return node.parent;
    }

    public T find(T data) {
        Node<T> node = map.get(data);
        if (node == null) {
            return null;
        }
        return findInternal(node).data;
    }

    public void union(T data1, T data2) {
        Node<T> node1 = map.get(data1), node2 = map.get(data2);
        if (node1 == null || node2 == null) {
            return;
        }
        node1 = findInternal(node1);
        node2 = findInternal(node2);
        if (node1.rank < node2.rank) {
            node1.parent = node2;
        } else if (node1.rank > node2.rank) {
            node2.parent = node1;
        } else {
            node1.parent = node2;
            ++node2.rank;
        }
    }

    private static class Node<T> {

        T data;

        Node<T> parent;

        //rank is not depth!!!
        int rank;

        Node(T data) {
            this.data = data;
            this.parent = this;
            this.rank = 0;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值