潍坊市论坛

首页 » 分类 » 定义 » 数据结构和算法四集合和映射
TUhjnbcbe - 2021/9/2 14:37:00
集合和映射

集合

集合的基本功能:

publicinterfaceSetE{voidadd(Ee);voidremove(Ee);booleancontains(Ee);intgetSize();booleanisEmpty();}基于二分搜索树的集合实现

publicclassBSTSetEextendsComparableEimplementsSetE{privateBSTEbst;publicBSTSet(){bst=newBST();}

Overridepublicvoidadd(Ee){bst.add(e);}

Overridepublicvoidremove(Ee){bst.del(e);}

Overridepublicbooleancontains(Ee){returnbst.contains(e);}

OverridepublicintgetSize(){returnbst.size();}

OverridepublicbooleanisEmpty(){returnbst.isEmpty();}}基于链表的集合实现

publicclassLinkedListSetEimplementsSetE{privateLinkedListElinkedList;publicLinkedListSet(){linkedList=newLinkedList();}

Overridepublicvoidadd(Ee){if(!contains(e)){linkedList.addFirst(e);}}

Overridepublicvoidremove(Ee){if(contains(e)){linkedList.removeElement(e);}}

Overridepublicbooleancontains(Ee){returnlinkedList.contains(e);}

OverridepublicintgetSize(){returnlinkedList.getSize();}

OverridepublicbooleanisEmpty(){returnlinkedList.isEmpty();}}时间复杂度分析操作LinkedListSetBSTSetaddO(n)平均情况:O(logn)最差情况:O(n)containsO(n)平均情况:O(logn)最差情况:O(n)removeO(n)平均情况:O(logn)最差情况:O(n)映射

映射的基本功能:

publicinterfaceMapK,V{voidadd(Kkey,Vvalue);Vremove(Kkey);booleancontains(Kkey);Vget(Kkey);voidset(Kkey,VnewValue);intgetSize();booleanisEmpty();}基于二分搜索树的映射实现

publicclassBSTMapKextendsComparableK,VimplementsMapK,V{privateclassNode{publicKkey;publicVvalue;publicNodeleft,right;publicNode(Kkey,Vvalue){this.key=key;this.value=value;this.left=null;this.right=null;}}privateNoderoot;privateintsize;//返回以node为根节点的二分搜索树中,key所在的节点privateNodegetNode(Nodenode,Kkey){if(node==null){returnnull;}if(key.

1
查看完整版本: 数据结构和算法四集合和映射