在 c++ 的unordered_map中查找最大键
Finding max key in an unordered_map in c++
这个问题与这个问题类似,但我需要在unordered_map(hashMap(而不是地图中找到它。 由于unordered_map中的元素显然是无序的,因此我不能使用类似问题中提到的逻辑。
那么,有没有办法(除了顺序迭代(找出unordered_map中的最大键? 也就是说,最好是O(1)
或O(logN)
而不是O(n)
?
谢谢!
不,就其本质而言,无序映射无法轻易提供其最大值,因此,如果无序列图是您所拥有的全部,则必须按顺序搜索。
但是,没有什么可以阻止您提供自己的类,该类派生自(或包含(无序映射并向其添加功能。在伪代码中,包含类可以如下所示:
class my_int_map:
unordered_int_map m_map; # Actual underlying map.
int m_maxVal = 0; # Max value (if m_count > 0).
bool m_count = 0; # Count of items with max value.
int getMaxVal():
# No max value if map is empty (throws, but you
# could return some sentinel value like MININT).
if m_map.size() == 0:
throw no_max_value
# If max value unknown, work it out.
if m_count == 0:
m_maxVal = m_map[0]
m_count = 0
for each item in m_map:
if item > m_maxVal:
m_maxVal = item
m_count = 1
else if item == m_maxVal:
m_count++
return m_maxVal
addVal(int n):
# Add it to real map first.
m_map.add(n)
# If it's only one in map, it's obviously the max.
if m_map.size() == 1:
m_maxVal = n
m_count = 1
return
# If it's equal to current max, increment count.
if m_count > 0 and n == m_maxVal:
m_count++
return
# If it's greater than current max, fix that.
if m_count > 0 and n > m_maxVal:
m_maxVal = n
m_count = 1
delIndex(int index):
# If we're deleting a largest value, we just decrement
# the count, but only down to zero.
if m_count > 0 and m_map[index] == m_maxVal:
m_count--
m_map.del(index)
这是对某些集合的标准优化,因为它提供了对某些属性的延迟评估,同时仍然缓存它以提高速度。
仅当您删除当前具有最高值的最后一个项目时,才会发生O(n)
搜索。
所有其他操作(获取最大值、添加、删除(如果不是最终最大项目(使用O(1)
成本保持最大值更新。
相关文章:
- 如何从map<pair<string,int>,pair<string,Array>>中迭代和查找?
- 使用STD :: MAP在数据及其性能问题中查找重复项.我可以预先分配吗?
- 查找并插入-STD :: MAP C
- 对于关键字查找,std::vector比std::map快
- 如何创建一个以键为输入并在C++std:map中查找值的模板函数
- 如何实现 std::map::查找包含两个结构'Pos'结构的比较逻辑,每个结构包含 x 和 y 坐标
- STD :: SET(或STD :: MAP)是否有一个提供基于值的查找的STL比较器?STD :: lands_les
- 如何有效查找大型std :: map
- STD :: MAP-如何查找或添加,然后可以在一次搜索中删除项目
- 标准::map 中的容错键查找
- std::map{'0',0}对在char'0'用作查找
- std::map:仅使用部分键类型进行比较和查找
- A* 路径查找中 std::map 性能的视觉C++性能问题
- STL MAP 应该使用 find() 或 [n] 标识符来查找 map 中的元素
- 使用 STL Map 查找该对中第一个元素的最低键对
- 哪个性能更快?具有 N 个派生类型的 vtable 查找,或具有 N 个元素的 std::map 查找
- 对在 std::map 的查找/插入上使用可升级锁感到困惑
- 检查 std::map 中是否存在 - 计数与查找
- 使用列表查找map中的元素
- 根据值查找map中的元素