在本文中,我們有一個包含不同元素的數組。我們需要打印數組中具有相同絕對值的正負值對,并按排序順序打印它們,例如 –
Input : arr[] = { 1, -1, 11, 12, 56, 77, -56, -12, -88}
Output : -1 1 -12 12 -56 56
Input : arr[] = {30, 40, 50, 77, -51, -50, -40}
Output : -40 40 -50 50
登錄后復制
尋找解決方案的方法
我們首先想到的方法是蠻力法,然后我們還想出了一種稱為高效法的方法。我們將討論這兩種方法。
蠻力法
在這種方法中,我們將用一個索引遍歷數組,并找到相同的絕對值但不同的索引。
示例
#include<bits/stdc++.h>
using namespace std;
int main() {
int arr[] = { 1, -1, 11, 12, 56, 77, -56, -12, -88 };
int n = sizeof(arr)/sizeof(int); // size of our array.
vector<int> nums; // the present pairs.
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
if(abs(arr[j]) == abs(arr[i])) { // finding the pairs.
nums.push_back(abs(arr[i]));
break;
// if we found the pair then we can just break as there are distinct elements in the array.
}
}
}
sort(nums.begin(), nums.end());
for(auto x : nums) // printing the pairs.
cout << -x << " " << x << " ";
}
登錄后復制
輸出
-1 1 -12 12 -56 56
登錄后復制
在這種方法中,我們使用兩個循環來遍歷數組并找到另一個元素;如果我們找到另一個元素,我們會從內循環中跳出以加快代碼運行速度?,F在我們使用了兩個for循環,整體的時間復雜度為O(N*N)。N是給定數組的大小,適用于較低的約束條件,但對于較高的約束條件來說并不好,所以現在我們將討論另一種方法。
高效方法
在這種方法中,我們將使用一個哈希映射,這將大大降低我們的時間復雜度。
示例
#include<bits/stdc++.h>
using namespace std;
int main() {
int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n = sizeof(arr)/sizeof(int); // size of our array.
map<int, int> found; // going to store the count of numbers found.
vector<int> nums; // the present pairs.
for(int i = 0; i < n; i++)
found[abs(arr[i])]++; // increasing the frequency of abs(arr[i]).
for(auto x : found) { // traversing the map.
if(x.second == 2) // if any numbers frequency is two then push it to nums.
nums.push_back(x.first);
}
for(auto x : nums) // printing the pairs.
cout << -x << " " << x << " ";
}
登錄后復制
輸出
-1 1 -4 4 -8 8 -9 9
登錄后復制
上述代碼的解釋
在這種方法中,我們使用哈希圖來存儲數字的頻率;當我們遍歷數組時,我們現在正在更新當前元素絕對值的頻率,因為您知道所有對的值都為 2,因此我們正在遍歷地圖。
如果任何數字的頻率為 2,然后我們將其存儲在 nums 中,最后,我們按排序順序打印值。 (由于地圖包含按排序順序排列的數字,因此我們不需要對數字向量進行排序)。
結論
在本文中,我們解決了查找對的問題使用散列技術計算數組中的正負值。我們還學習了解決這個問題的C++程序以及解決這個問題的完整方法(正常且高效)。我們可以用其他語言比如C、java、python等語言來編寫同樣的程序。我們希望這篇文章對您有所幫助。
以上就是使用C++找到數組中的正負值對的詳細內容,更多請關注www.xfxf.net其它相關文章!






