题目描述
给你一个矩阵 mat
,其中每一行的元素都已经按 递增 顺序排好了。请你帮忙找出在所有这些行中 最小的公共元素。
如果矩阵中没有这样的公共元素,就请返回 -1
。
示例:
输入:mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]] 输出:5
提示:
1 <= mat.length, mat[i].length <= 500
1 <= mat[i][j] <= 10^4
mat[i]
已按递增顺序排列。
解题思路
class Solution {
public:
int smallestCommonElement(vector<vector<int>>& mat) {
unordered_map<int,int> mp;
if(mat.size()<=1) return -1;
int m = mat.size();
for(int i=0;i<m;++i){
unordered_set<int> st(mat[i].begin(),mat[i].end());
for(auto it : st) mp[it]++;
}
int ans = INT_MAX;
for(auto it : mp){
if(it.second == m) ans = min(ans,it.first);
}
return (ans == INT_MAX)?-1:ans;
}
}