在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP