Find Smallest Common Element in All Rows
给一个2d数组, 里面每个row都是严格递增排序的, 求最小的row公共元素.
排序所以用二叉搜索, 正好std::binary_search返回的是true/false.
class Solution {
public:
int smallestCommonElement(vector<vector<int>>& mat) {
int n = mat.size();
int res = 0;
for(int i = 0; i < mat[0].size(); i++){
bool found = true;
for(int j = 1; j < n; j++){
if(!binary_search(mat[j].begin(), mat[j].end(), mat[0][i])){
found = false;
break;
}
}
if(found)
return mat[0][i];
}
return -1;
}
};