给你一个矩阵 mat
,其中每一行的元素都已经按 递增 顺序排好了。请你帮忙找出在所有这些行中 最小的公共元素。
如果矩阵中没有这样的公共元素,就请返回 -1
。
示例:
复制代码
1
2
3输入: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]
已按递增顺序排列。
C++
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47class 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内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复