在 C++ 中查詢給定按行排序的矩陣所有行中的常見元素
假設我們有一個矩陣,其中每一行都被排序。我們要編寫一個函式來查詢每行中的常見元素。假設矩陣如下所示 -
結果將為 5。
為了解決這個問題,我們將使用基於雜湊的方法。當行未排序時,也可以使用此方法。我們必須按照以下步驟進行操作 -
我們將建立一個雜湊表,所有鍵都是兩個 1 的不同元素。所有值都將為 0
迴圈遍歷矩陣中的每個元素,如果數字存在於雜湊表中,則將計數增加 1。最後檢查是否有一些值的數量與矩陣的行號相同。如果存在,則存在於每一行中。(假設一個值不會在某一行中重複)
示例
#include<iostream> #include<unordered_map> #define M 4 #define N 5 using namespace std; int getCommonElement(int matrix[M][N]) { unordered_map<int, int> count; int i, j; for (i = 0; i < M; i++) { count[matrix[i][0]]++; for (j = 1; j < N; j++) { if (matrix[i][j] != matrix[i][j - 1]) count[matrix[i][j]]++; } } for (auto ele : count) { if (ele.second == M) return ele.first; } return -1; } int main() { int matrix[M][N] = { { 1, 2, 3, 4, 5 }, { 2, 4, 5, 8, 10 }, { 3, 5, 7, 9, 11 }, { 1, 3, 5, 7, 9 }, }; int result = getCommonElement(matrix); if (result == -1) cout << "No common element has found"; else cout << "Common element is " << result; }
輸出
Common element is 5
廣告