当前位置:网站首页>【集合】HashSet和ArrayList的查找Contains()时间复杂度
【集合】HashSet和ArrayList的查找Contains()时间复杂度
2022-08-10 11:42:00 【檀越剑指大厂】
HashSet和ArrayList的查找Contains()时间复杂度
ArrayList本质就是通过数组实现的,查找一个元素是否包含要用到遍历,时间复杂度是O(N)
HashSetHashSet的查找是通过HashMap的KeySet来实现的,判断是否包含某个元素的实现,时间复杂度是O(1)
//ArrayList判断是否包含某个元素的源码实现:
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;
}
//HashSet判断是否包含某个元素的源码实现:
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))))//部分情况下可能会继续遍历链表定位
return e;
} while ((e = e.next) != null);
}
}
return null;
}
边栏推荐
- 你是怎么知道数据库 Htap 能力强弱的?怎么能看出来
- So delicious!Since using this interface artifact, my team efficiency has increased by 60%!
- 配置druid数据源「建议收藏」
- 日记16
- LeetCode 82. Remove Duplicate Elements in Sorted List II
- 16. Getting Started with Pytorch Lightning
- Does your child lack self-discipline?Ape Counseling: Pay attention to "blank" in the schedule to give children more control
- 配置swagger
- Apple bucks the trend and expands iPhone 14 series stocking, with a total of 95 million units
- LeetCode 369. Plus One Linked List(链表加1)
猜你喜欢

嘉为蓝鲸荣获工信部“数字技术融合创新应用解决方案”

太香了!自从用了这款接口神器,我的团队效率提升了 60%!

Analysis of the implementation principle of UUID from the perspective of source code

three.js blur glass effect

You have a Doubaqiong thesaurus, please check it

StoneDB Document Bug Hunting Season 1

培训机构学习费用是多少呢?

你是怎么知道数据库 Htap 能力强弱的?怎么能看出来

时间序列的数据分析(五):简单预测法

个推数据资产管理经验 | 教你打造数据质量心电图,智能检测数据“心跳”异常
随机推荐
search--09
LeetCode 362. Design Hit Counter
OPNsense安装配置Zenarmor
LT8911EXB MIPI CSI/DSI转EDP信号转换
网络基础(第一节)
这三个 Go 水平自测题,你手写不出来还是先老实上班吧,过来看看
人脸考勤是选择人脸比对1:1还是人脸搜索1:N?
Samsung plans to start producing semiconductor components in Vietnam in 2023
Excel function formulas - LOOKUP function
Servlet---解决post请求中中文乱码问题
毕业总结
Dining (网络流)
jlink and swd interface definition
22年BATJ大厂必问面试题(复盘):JVM+微服务+多线程+锁+高并发
leetcode/两个链表的第一个重合节点
LeetCode 445. Adding Two Numbers II
一文读懂NFT数字藏品为何风靡全球?
LeetCode 138. Copy a linked list with random pointers
Pulling drills - 56 Finding the right interval
个推数据资产管理经验 | 教你打造数据质量心电图,智能检测数据“心跳”异常