题目描述:
Given a matrix, find a element that appear in all the rows in the matrix.You can assume that there is only one such element.
样例:
For example:
Given a matrix:
[
[2,5,3],
[3,2,1],
[1,3,5]
]
return 3;
思路讲解:这里我读一下题目,其就是对于矩阵中的每一行都存在一个相同的数。比如上面的3,我的思路是每一次都在上面一行的基础上找重复出现的数,这样滚动找,由于我们的题目说只有一个数,故我们只会得到一个结果。这里由于我们需要不断的对元素组进行查找,所以我们可以使用set方法。
就拿上面的矩阵举个例子:
第一行 是2,5,3
第二行在第一行的基础上查找得到3,2
第三行在第二行的基础上查找得到重复元素有3
故最终结果就是3了。
代码详解:
class Solution {
public:
/**
* @param Matrix: the input
* @return: the element which appears every row
*/
int FindElements(vector<vector<int>> &Matrix) {
// write your code here
set<int>hash1;
set<int>hash2;
int m=Matrix.size();
int n=Matrix[0].size();
for(int i=0;i<n;i++)
{
hash1.insert(Matrix[0][i]);
}
for(int i=1;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i%2==1){
if(hash1.find(Matrix[i][j])!=hash1.end()){
hash2.insert(Matrix[i][j]);
}
}else{
if(hash2.find(Matrix[i][j])!=hash2.end()){
hash1.insert(Matrix[i][j]);
}
}
}
if(i%2==1){
hash1.clear();
}else{
hash2.clear();
}
}
if(m%2==0){
return *hash2.begin();
}else{
return *hash1.begin();
}
}
};