[LeetCode] Lucky Numbers in a Matrix

1380. Lucky Numbers in a Matrix

Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
vector<int> luckyNumbers (vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
vector<int> r(n,INT_MAX), c(m,INT_MIN);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
r[i] = min(r[i], matrix[i][j]);
c[j] = max(c[j], matrix[i][j]);
}
}
vector<int> res;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(r[i] == matrix[i][j] and c[j] == matrix[i][j]) res.push_back(matrix[i][j]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/19/PS/LeetCode/lucky-numbers-in-a-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.