哈希表的最差復雜度是n2_給定數組A []和數字X,請檢查A []中是否有對X | 使用哈希O(n)時間復雜度| 套裝1...

哈希表的最差復雜度是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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540509.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540509.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540509.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

一文讀懂深度學習框架下的目標檢測(附數據集)

從簡單的圖像分類到3D位置估算&#xff0c;在機器視覺領域里從來都不乏有趣的問題。其中我們最感興趣的問題之一就是目標檢測。 如同其他的機器視覺問題一樣&#xff0c;目標檢測目前為止還沒有公認最好的解決方法。在了解目標檢測之前&#xff0c;讓我們先快速地了解一下這個領…

[轉載] Python-Strings

參考鏈接&#xff1a; Python成員資格和身份運算符 &#xff5c; in, not in, is, is not Strings 介紹 String是Python中最常用的類型。僅僅用引號括起字符就可以創建string變量。字符串使用單引號或雙引號對Python來說是一樣的。 var1 Hello World! var2 "Pyth…

aes-128算法加密_加密算法問題-人工智能中的一種約束滿意問題

aes-128算法加密The Crypt-Arithmetic problem in Artificial Intelligence is a type of encryption problem in which the written message in an alphabetical form which is easily readable and understandable is converted into a numeric form which is neither easily…

讀書筆記《集體智慧編程》Chapter 2 : Make Recommendations

本章概要本章主要介紹了兩種協同過濾&#xff08;Collaborative Filtering&#xff09;算法&#xff0c;用于個性化推薦&#xff1a;基于用戶的協同過濾&#xff08;User-Based Collaborative Filtering&#xff0c;又稱 K-Nearest Neighbor Collaborative Filtering&#xff0…

[轉載] python中的for循環對象和循環退出

參考鏈接&#xff1a; Python中循環 流程控制-if條件 判斷條件&#xff0c;1位true&#xff0c;0是flesh&#xff0c;成立時true&#xff0c;不成立flesh&#xff0c;not取反 if 1; print hello python print true not取反&#xff0c;匹配取反&#xff0c;表示取非1…

設計一個應用程序,以在C#中的按鈕單擊事件上在MessageBox中顯示TextBox中的文本...

Here, we took two controls on windows form that are TextBox and Button, named txtInput and btnShow respectively. We have to write C# code to display TextBox’s text in the MessageBox on Button Click. 在這里&#xff0c;我們在Windows窗體上使用了兩個控件&…

Oracle優化器:星型轉換(Star Query Transformation )

Oracle優化器&#xff1a;星型轉換&#xff08;Star Query Transformation &#xff09;Star query是一個事實表&#xff08;fact table&#xff09;和一些維度表&#xff08;dimension&#xff09;的join。每個維度表都跟事實表通過主外鍵join&#xff0c;且每個維度表之間不j…

[轉載] python循環中break、continue 、exit() 、pass的區別

參考鏈接&#xff1a; Python中的循環和控制語句(continue, break and pass) 1、break&#xff1a;跳出循環&#xff0c;不再執行 用在while和for循環中 用來終止循環語句&#xff0c;即循環條件沒有False條件或者序列還沒被完全遞歸完&#xff0c;也會停止執行循環語句 如果…

JavaScript | 聲明數組并使用數組索引分配元素的代碼

Declare an array, assign elements by indexes and print all elements in JavaScript. 聲明一個數組&#xff0c;通過索引分配元素&#xff0c;并打印JavaScript中的所有元素。 Code: 碼&#xff1a; <html><head><script>var fruits [];fruits[0]"…

[轉載] Python入門(輸入/輸出、數據類型、條件/循環語句)

參考鏈接&#xff1a; Python中的循環技術 在介紹之前我們先來看看計算機的三個根本性基礎&#xff1a; 1.計算機是執行輸入、運算、輸出的機器 2.程序是指令和數據的集合 3.計算機的處理方式有時與人們的思維習慣不同 &#xff08;以上是引自《計算機是怎樣跑起來的》…

第5章 函數與函數式編程

第5章 函數與函數式編程 凡此變數中函彼變數者&#xff0c;則此為彼之函數。 ( 李善蘭《代數學》) 函數式編程語言最重要的基礎是λ演算&#xff08;lambda calculus&#xff09;&#xff0c;而且λ演算的函數可以傳入函數參數&#xff0c;也可以返回一個函數。函數式編程 (簡稱…

mcq 隊列_人工智能能力問答中的人工智能概率推理(MCQ)

mcq 隊列1) Which of the following correctly defines the use of probabilistic reasoning in AI systems? In situations of uncertainty, probabilistic theory can help us give an estimate of how much an event is likely to occur or happen.It helps to find the pr…

[轉載] Python中的xrange和range的區別

參考鏈接&#xff1a; Python中的range()和xrange() 在python2 中 range(start,end,step)返回一個列表&#xff0c;返回的結果是可迭代對象&#xff0c;但不是迭代器。iter()轉化為列表迭代器。xrange()返回的是一個序列&#xff0c;他也是可迭代對象&#xff0c;但不是迭代…

Kubernetes基礎組件概述

本文講的是Kubernetes基礎組件概述【編者的話】最近總有同學問Kubernetes中的各個組件的相關問題&#xff0c;其實這些概念內容在官方文檔中都有&#xff0c;奈何我們有些同學可能英文不好&#xff0c;又或者懶得去看&#xff0c;又或者沒有找到&#xff0c;今天有時間就專門寫…

c語言將鏈表寫入二進制文件_通過逐級遍歷將二進制樹轉換為單鏈表的C程序

c語言將鏈表寫入二進制文件Problem statement: Write a C program to convert a binary tree into a single linked list by traversing level-wise. 問題陳述&#xff1a;編寫一個C程序&#xff0c;通過逐級遍歷將二進制樹轉換為單個鏈表 。 Example: 例&#xff1a; The ab…

[轉載] C Primer Plus 第6章 C控制語句 6.16 編程練習及答案

參考鏈接&#xff1a; 用Python打印金字塔圖案的程序 2019獨角獸企業重金招聘Python工程師標準>>> 1、編寫一個程序&#xff0c;創建一個具有26個元素的數組&#xff0c;并在其中存儲26個小寫字母。并讓該程序顯示該數組的內容。 #include int main (void) { …

C# String和string的區別

C#中同時存在String與string MSDN中對string的說明&#xff1a; string is an alias for String in the .NET Framework。string是String的別名而已&#xff0c;string是c#中的類&#xff0c;String是Framework的類&#xff0c;C# string 映射為 Framework的 String。如果用str…

要求用戶在Python中輸入整數| 限制用戶僅輸入整數值

input() function can be used for the input, but it reads the value as a string, then we can use the int() function to convert string value to an integer. input()函數可用于輸入&#xff0c;但它將值讀取為字符串&#xff0c;然后可以使用int()函數將字符串值轉換為…

[轉載] python——if語句、邏輯運算符號

參考鏈接&#xff1a; 用Python鏈接比較運算符 1.if條件判斷語句&#xff1a; if 要判斷的條件(True): 條件成立的時候&#xff0c;要做的事情 elif 要判斷的條件(True): .... elif 要判斷的條件(True): .... else: 條件不成立的時候要做的事情 示例&#xff1a; 判斷學生…

洛谷 P2689 東南西北【模擬/搜索】

題目描述 給出起點和終點的坐標及接下來T個時刻的風向(東南西北)&#xff0c;每次可以選擇順風偏移1個單位或者停在原地。求到達終點的最少時間。 如果無法偏移至終點&#xff0c;輸出“-1”。 輸入輸出格式 輸入格式&#xff1a; 第一行兩個正整數x1,y1&#xff0c;表示小明所…