Since each row is sorted and contains only unique elements, we can count the occurrences of each number across all rows. The smallest number that appears in every row is the answer.
classSolution {
public:int smallestCommonElement(vector<vector<int>>& mat) {
unordered_map<int, int> cnt;
int m = mat.size();
for (auto& row : mat) for (int x : row) cnt[x]++;
int ans = INT_MAX;
for (auto& [k, v] : cnt) if (v == m) ans = min(ans, k);
return ans == INT_MAX ?-1: ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
funcsmallestCommonElement(mat [][]int) int {
cnt:=map[int]int{}
m:= len(mat)
for_, row:=rangemat {
for_, x:=rangerow {
cnt[x]++ }
}
ans:=1<<31-1fork, v:=rangecnt {
ifv==m&&k < ans {
ans = k }
}
ifans==1<<31-1 {
return-1 }
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintsmallestCommonElement(int[][] mat) {
Map<Integer, Integer> cnt =new HashMap<>();
int m = mat.length;
for (int[] row : mat) for (int x : row) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = Integer.MAX_VALUE;
for (var e : cnt.entrySet()) if (e.getValue() == m) ans = Math.min(ans, e.getKey());
return ans == Integer.MAX_VALUE?-1 : ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funsmallestCommonElement(mat: Array<IntArray>): Int {
val cnt = mutableMapOf<Int, Int>()
val m = mat.size
for (row in mat) for (x in row) cnt[x] = cnt.getOrDefault(x, 0) + 1return cnt.filter { it.value== m }.keys.minOrNull() ?: -1 }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defsmallestCommonElement(self, mat: list[list[int]]) -> int:
from collections import Counter
m = len(mat)
cnt = Counter()
for row in mat:
cnt.update(row)
for x in sorted(cnt):
if cnt[x] == m:
return x
return-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnsmallest_common_element(mat: Vec<Vec<i32>>) -> i32 {
use std::collections::HashMap;
let m = mat.len();
letmut cnt = HashMap::new();
for row in&mat {
for&x in row {
*cnt.entry(x).or_insert(0) +=1;
}
}
letmut ans =i32::MAX;
for (&k, &v) in&cnt {
if v == m && k < ans {
ans = k;
}
}
if ans ==i32::MAX { -1 } else { ans }
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
smallestCommonElement(mat: number[][]):number {
constcnt: Record<number, number> = {};
constm=mat.length;
for (constrowofmat) for (constxofrow) cnt[x] = (cnt[x] ??0) +1;
letans=Infinity;
for (constkincnt) if (cnt[k] ===m&&+k<ans) ans=+k;
returnans===Infinity?-1 : ans;
}
}