Find Elements in Matrix-LintCode

本文介绍了一种算法,用于寻找给定矩阵中唯一出现在所有行的元素。通过使用集合存储每行的不同元素,并逐步筛选出共同存在的元素实现。

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

思路:
取出第一行数组,判断其中的元素是否存在于剩余的数组中,将存在的存入新的数组,再进行判断。

#ifndef C737_H
#define C737_H
#include<iostream>
#include<vector>
#include<set>
using namespace std;
class Solution {
public:
    /**
    * @param Matrix: the input
    * @return: the element which appears every row
    */
    int FindElements(vector<vector<int>> &Matrix) {
        // write your code here
        vector<set<int>> v;
        set<int> set;
        for (int i = 0; i < Matrix.size(); ++i)
        {
            set.clear();
            for (auto c : Matrix[i])
            {
                set.insert(c);
            }
            v.push_back(set);
        }
        vector<int> tmp;
        vector<int> res;
        for (auto it = Matrix[0].begin(); it != Matrix[0].end(); ++it)
        {
            tmp.push_back(*it);//取出第一行数组
        }
        for (int i = 1; i < v.size(); ++i)
        {
            for (auto c : tmp)
            {
                if (v[i].find(c) != v[i].end())
                    res.push_back(c);//将存在于剩余数组的元素存入新的数组
            }
            tmp = res;//更新tmp的值,准备进行新的判断
            res.clear();
        }
        return tmp[0];
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值