给你一个矩阵 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 <= 5001 <= mat[i][j] <= 10^4mat[i]已按递增顺序排列。
C++
class Solution {
public:
int smallestCommonElement(vector<vector<int>>& mat)
{
int m=mat.size();
int n=mat[0].size();
for(int k=0;k<n;k++)
{
int count=0;
for(int i=1;i<m;i++)
{
int idx=upper_bound(mat[i].begin(),mat[i].end(),mat[0][k])-mat[i].begin();
if(idx==0)
{
if(mat[i][0]==mat[0][k])
{
count++;
if(count==m-1)
{
return mat[0][k];
}
}
else
{
break;
}
}
else
{
if(mat[0][k]==mat[i][idx-1])
{
count++;
if(count==m-1)
{
return mat[0][k];
}
}
else
{
break;
}
}
}
}
return -1;
}
};
最后
以上就是含蓄便当最近收集整理的关于leetcode 1198. 找出所有行中最小公共元素(C++)的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复