当前位置:网站首页>[Collection] HashSet and ArrayList lookup Contains() time complexity
[Collection] HashSet and ArrayList lookup Contains() time complexity
2022-08-10 12:32:00 【Danapati sword refers to companies】
HashSet和ArrayList的查找Contains()时间复杂度
ArrayListEssence is through the array,Find if an element contains to use traversal,时间复杂度是O(N)
HashSetHashSet的查找是通过HashMap的KeySet来实现的,Determine whether contains an element of true,时间复杂度是O(1)
//ArrayListDetermine whether contains an element of the source code to achieve:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++) //从头遍历
if (o.equals(elementData[i]))
return i;
}
return -1;
}
//HashSetDetermine whether contains an element of the source code to achieve:
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//直接通过hash确定元素位置,不用从头遍历
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))//Some cases may continue to traverse the list to locate
return e;
} while ((e = e.next) != null);
}
}
return null;
}
边栏推荐
猜你喜欢
16、Pytorch Lightning入门
太香了!自从用了这款接口神器,我的团队效率提升了 60%!
郭晶晶家的象棋私教,好家伙是个机器人
StarRocks on AWS 回顾 | Data Everywhere 系列活动深圳站圆满结束
第5章 虚拟存储器
Network Fundamentals (Section 1)
A detailed explanation of implementation api embed
IDC第一的背后,阿里云在打造怎样的一朵“视频云”?
吃透Chisel语言.36.Chisel实战之以FIFO为例(一)——FIFO Buffer和Bubble FIFO的Chisel实现
2016,还是到了最后
随机推荐
Golang分布式应用之etcd
leetcode/两个链表的第一个重合节点
Samsung plans to start producing semiconductor components in Vietnam in 2023
正则表达式常用示例
OPNsense安装配置Zenarmor
HDU 4372:Count the Buildings (Stirling数)
吃透Chisel语言.36.Chisel实战之以FIFO为例(一)——FIFO Buffer和Bubble FIFO的Chisel实现
迈矽科推出高性能77GHz毫米波雷达芯片,尚未量产就已获数万颗订单
LeetCode 369. Plus One Linked List(链表加1)
培训机构学习费用是多少呢?
Color map and depth map to point cloud
搜索--09
蚂蚁金服+拼多多+抖音+天猫(技术三面)面经合集助你拿大厂offer
dedecms支持Word内容一键导入
So delicious!Since using this interface artifact, my team efficiency has increased by 60%!
【mysql】explain介绍[通俗易懂]
开源的作者,也有个生活问题
ssm框架搭建过程[通俗易懂]
可视化服务编排在金融APP中的实践
面试官:你们是如何保证接口的幂等性?