Week1-3Quick Union

来源:互联网 发布:java七牛上传视频接口 编辑:程序博客网 时间:2024/06/06 09:53

Data Structure

  • Integer array id[] of size N
  • Root of i isid[id[id[…id[i]…]]](keep going until it doesn’t change)

Operations

  • Find( p, q ): check if p and q have the same root
  • Union( p, q ): to merge components containing p and q, set id of p’s root to the id of q’s root

Implementation

    public class QuickUnionUF    {        private int[] id;        public QuickUnionUF( int N )        {            id = new int[N];            for( int i = 0; i< N; i++ )            {                id[i] = i;            }        }         private int root( int i )        {            // chase parent pointer until reach root            while( i != id[i] )            {                i = id[i];            }            return i;        }        public boolean connected( int p, int q )        {            return root( p ) == root( q );        }        public void union( int p, int q )        {            int i = root( p ),                j = root( q );            id[i] = j;        }    }

Cost Model

Algorightm Initialize Union Find quick-find O(N) O(N) O(1) quick-union O(N) O(N) O(N)

Defects

这里写图片描述

0 0
原创粉丝点击