哈希表的最差复杂度是n2

Prerequisite:

先决条件:

  • Hashing data structure

    散列数据结构

Problem statement:

问题陈述:

Given an array and a sum X, fins any pair which sums to X. Expected time complexity O(n).

给定一个数组和一个X ,对求和为X的任何一对进行求和。 预期时间复杂度O(n)

Example:

例:

Input array:
[4, -1, 6, 5, -2, 2]
Sum, X=2
Output:
Pair {4,-2}
Explanation:
4+(-2)=2 and thus the pair is {4,-2}

Solution:

解:

Obviously, in brute force, we can solve it by checking each pair sums to X or not. In the worst case, it will take O(n2) which is too costly for the problem. Still, the algorithm would be like the following:

显然,在蛮力中,我们可以通过检查每对和是否等于X来解决。 在最坏的情况下,将花费O(n 2 ) ,这对于该问题而言过于昂贵。 尽管如此,该算法仍将如下所示:

For i=0:n-1
For j=i+1: n-1
If arr[i]+arr[j]==X
Return pair {arr[i],arr[j]}

To solve this efficiently, we will use hashing. What we need to create is a hash table which will be used as our lookup table. The idea is to lookup whether X-current_element exists in the hash table or not. If we find any element in the hash table, then obviously
{X-current_element, current_element} is our desired pair.

为了有效解决此问题,我们将使用哈希。 我们需要创建一个哈希表,该哈希表将用作我们的查找表。 这个想法是要查找哈希表中是否存在X-current_element 。 如果我们在哈希表中找到任何元素,那么显然
{X-current_element,current_element}是我们想要的对。

Now, we can create a lookup table by simply inserting each element. Then in another loop, we can start finding whether X-current_element is in the hash table or not. Following is the two-pass algorithm,

现在,我们只需插入每个元素即可创建查找表。 然后在另一个循环中,我们可以开始查找X-current_element是否在哈希表中。 以下是两次通过算法,

Create a hash table using set

使用set创建哈希表

unordered_set<int> myset;
//first pass->building the hash table
For i=0 to n-1
current_element=arr[i]
Add current_element to look up table, myset if it’s not there
End for

Find the pair

找到一对

//second pass-> finding the pair using the hash table built
For i=0 to n-1
current_element=arr[i]
if(X-current_element is in myset)
the desired pair is { current_element , X-current_element }
and return
End for

The time complexity of the algorithm is of course O(n) and space complexity is also O(n) for the hash table.

该算法的时间复杂度当然是O(n),而哈希表的空间复杂度也是O(n)。

Now, we can further optimize the above algorithm into a single pass.

现在,我们可以将上述算法进一步优化为一次通过。

Instead of creating the hash table in a separate pass, we can do both searching and creating in one pass. The idea is if X-current_element is in the hash table then we are done, otherwise, add this current_element to the hash table.

除了在单独的过程中创建哈希表,我们还可以一次完成搜索和创建过程。 这个想法是,如果X-current_element在哈希表中,那么我们完成了,否则,请将此current_element添加到哈希表中。

So the algorithm would be:

因此,算法为:

//both searching and looking at a time
For i=0 to n-1
current_element=arr[i]
if(X-current_element is in myset)
the desired pair is { current_element , X-current_element }
and return
Else
Add current_element to myset
End for

So, how it guarantees to work?

那么,它如何保证工作呢?

We can show that by our example. Where input array is [4, -1, 6, 5, -2, 2]
If we have used the two-pass algorithm then, we have got {4,-2} as a pair where 4 would be the current_element and-2 would be the X-current_element.

我们可以通过示例来证明这一点。 输入数组为[4,-1,6,5,-2,2]
如果我们使用了两次遍历算法,那么我们将{4,-2}作为一对,其中4是current_element ,-2是X-current_element

But if we use the one-pass algorithm we would get the pair as {-2, 4} where -2 would be the current_element and 4 would be X-current_element.

但是,如果使用单次通过算法,则该对将为{-2,4},其中-2为current_element,而4为X-current_element

The reason is when we have 4 as our current_element in our one-pass algorithm then the hash table is empty. Thus we simply add 4.

原因是当我们在一次通过算法中将4作为current_element时 ,哈希表为空。 因此,我们只需添加4。

But when we process -2 as our current_element we have X-(-2) to look for which is 2-(-2) and 4 now exists. So the thing is the one pass is guaranteed to work. Only it will return the pair in reverse order.

但是,当我们将-2作为current_element处理时,我们有X-(-2)来寻找哪个是2-(-2)且现在存在4。 因此,事情是一站式保证有效。 只有它会以相反的顺序返回该对。

The time & space complexity of the one-pass algorithm is of course same as the two-pass algorithm since it's big O notation.

一遍算法的时间和空间复杂度当然与二遍算法相同,因为它的O表示法很大。

C++ implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
pair<int, int> find_pair_sum(vector<int> arr, int n, int X)
{
unordered_set<int> myset;
for (int i = 0; i < n; i++) {
//pair exists current_element, X-current_element
if (myset.find(X - arr[i]) != myset.end()) {
return make_pair(arr[i], X - arr[i]);
}
//if arr[i] already not there
else if (myset.find(arr[i]) == myset.end())
myset.insert(arr[i]);
}
return make_pair(INT_MAX, INT_MAX);
}
int main()
{
cout << "Enter number of input elements,n\n";
int n;
cin >> n;
cout << "Enter the input elements\n";
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Enter sum, X\n";
int X;
cin >> X;
pair<int, int> p = find_pair_sum(arr, n, X);
if (p.first == INT_MAX && p.second == INT_MAX)
cout << "No pairs found\n";
else
cout << "The pairs are : " << p.first << ", " << p.second << endl;
return 0;
}

Output:

输出:

Enter number of input elements,n
6
Enter the input elements
4 -1 6 5 2 -2
Enter sum, X
2
The pairs are : -2, 4

翻译自: https://www.includehelp.com/data-structure-tutorial/given-an-array-a-and-number-x-check-for-pair-in-a-with-sum-x-set-1.aspx

哈希表的最差复杂度是n2

哈希表的最差复杂度是n2_给定数组A []和数字X,请检查A []中是否有对X | 使用哈希O(n)时间复杂度| 套装1...相关推荐

  1. [九度][何海涛] 旋转数组的最小数字

    题目描述: 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转.输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素.例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转 ...

  2. 算法学习Day1——C之哈希表

    思想:使用哈希函数将键映射到存储桶. 想要插入一个新的键,哈希函数将决定该键该分配到哪个桶中,并将该键存储在相应的桶中. 想要搜索一个键的时候,哈希表使用哈希函数来查找相应的桶,并在特定的桶中进行搜索 ...

  3. Berkeley DB的数据存储结构——哈希表(Hash Table)、B树(BTree)、队列(Queue)、记录号(Recno)...

    Berkeley DB的数据存储结构 BDB支持四种数据存储结构及相应算法,官方称为访问方法(Access Method),分别是哈希表(Hash Table).B树(BTree).队列(Queue) ...

  4. 数据结构与算法笔记(十五)—— 散列(哈希表)

    一.前沿 1.1.直接寻址表 当关键字的全域U比较小时,直接寻址是一种简单而有效的技术.假设某应用要用到一个动态集合,其中每个元素都有一个取自全域U={0,1,-,m-1)的关键字,此处m是一个不很大 ...

  5. 【从蛋壳到满天飞】JS 数据结构解析和算法实现-哈希表

    前言 [从蛋壳到满天飞]JS 数据结构解析和算法实现,全部文章大概的内容如下: Arrays(数组).Stacks(栈).Queues(队列).LinkedList(链表).Recursion(递归思 ...

  6. 除留余数法构造哈希表_哈希表算法原理

    基本概念 哈希表(Hash Table)是一种根据关键字直接访问内存存储位置的数据结构.通过哈希表,数据元素的存放位置和数据元素的关键字之间建立起某种对应关系,建立这种对应关系的函数称为哈希函数. 哈 ...

  7. 【哈希】关于哈希表和哈希函数的理解与应用

    0.概述 哈希,或者说散列,在教科书上写的都比较详细,通常包括的内容有散列的方法,散列冲突的解决等.本文暂且不表这些基础知识,更多的重点在于哈希的一些应用和题目,对于哈希表.哈希函数从来没有学习过或者 ...

  8. 用了十年竟然都不对,Java、Rust、Go主流编程语言的哈希表比较

    哈希表(HashMap.字典)是日常编程当中所经常用到的一种数据结构,程序员经常接解到的大数据Hadoop技术栈.Redis缓存数据库等等最近热度很高的技术,其实都是对键值(key-value)数据的 ...

  9. LeetCode哈希表(哈希集合,哈希映射)

    文章目录 哈希表 1.原理 2.复杂度分析 题目&推荐列表 哈希集合的应用 0.常用解题模板 1.lc217 存在重复元素 2.lc136 只出现一次的数字 3.快乐数 哈希映射的应用 0.常 ...

最新文章

  1. Ubuntu Linux经典著作
  2. 线程通信问题--生产者和消费者问题
  3. 两个不同的进程 虚拟地址相同_记一次阿里面试题:都有哪些进程间通信方式?麻烦你不要再背了...
  4. 计算机网络之物理层:3、奈式准则和香农公式
  5. 手工查杀myplayer病毒
  6. 机器学习中训练集和测试集归一化(matlab版)
  7. v-for中为何要使用key
  8. HTML5的文档声明
  9. nacos的命名空间
  10. java将前端传给后端的文字写入到word中
  11. EFR32BG22 Thunderboard Kit 学习笔记总结
  12. 普通的视觉工程师的待遇是怎样的?
  13. virtualxposed使用教程_VirtualXposed 使用方法教程 —— 教您不 Root 用上强悍的 Xposed 框架 | 软件库...
  14. 普通话测试软件哪个不要钱,普通话测试软件哪个好_普通话测试软件靠谱吗_不要钱的普通话测试软件...
  15. Windows 10(Office 2019)下安装mathtype 6.9/7.4以及相关冲突问题解决
  16. 科学松鼠会压缩感知科普文章两篇:“压缩感知与单像素相机(陶哲轩)”“填补空白:用数学方法将低分辨率图像变成高分辨率图像(Jordan Ellenberg)
  17. 【前端echatrs图表框架】使用echarts实现雷达图
  18. 传智播客截图工具_Hanselminutes播客183:直播! 小工具,高清,网络摄像头,4G等...
  19. 2019 ICPC 南昌网络赛 H. The Nth Item
  20. VMware使用2 ---虚拟磁盘管理工具vmware-vdiskmanager

热门文章

  1. duino例程 stm32_stm32duino
  2. fastexcel读取excel追加写入sheet页_python笔记52:python操作excel
  3. PHP递归删除目录面试题,PHP 递归删除目录中文件
  4. two+few+arguments+php,PHP5.5 ~ PHP7.2 新特性整理
  5. php 开源 采集,迅睿CMS 火车头内容采集
  6. php使用webservivce_JWS服务开发使用指南
  7. linux后台启动脚本nohup,linux下后台执行shell脚本nohup
  8. 【译】Googler如何解决编程问题
  9. 10. Python面向对象
  10. leetcode393. UTF-8 Validation