lintcode---Find Elements in Matrix

本文介绍了一种寻找矩阵中所有行共有的唯一元素的方法。通过使用集合数据结构逐步筛选,确保找到的元素出现在每一行中。示例代码展示了如何实现这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:
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();
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值