Give you a matrix mat
in which each row of the elements are already lined up in ascending order. Please help find the smallest in all of these lines common elements.
If the matrix is no such common elements, please return -1
.
Example: Input: MAT = [[ . 1 , 2 , . 3 , . 4 , . 5 ], [ 2 , . 4 , . 5 , . 8 , 10 ], [ . 3 , . 5 , . 7 , . 9 , . 11 ], [ . 1 , . 3 , . 5 , 7 , 9 ]] output: 5
solution:
Violent solution is to use a hash record per line and then compare
Code
class Solution { public: unordered_map<int, int> umap[510]; int smallestCommonElement(vector<vector<int>>& mat) { if (mat.empty() || mat[0].empty()) return -1; for (int i = 0; i < mat.size(); i++) { for (int j = 0; j < mat[0].size(); j++) { umap[i][mat[i][j]]++; } } for (int j = 0; j < mat[0].size(); j++) { int find = 1; int findNum = mat[0][j]; for (int i = 1; i < mat.size(); i++) { if (umap[i][findNum] == 0) { find = 0; break; } } if (find == 1) { return findNum; } } return -1; } };