LeetCode 1380. Lucky Numbers in a Matrix

Question

Given a m * 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.

Example

1
2
3
4
5
6
7
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.

Solution

一开始想到到的就是暴力解法,搜索每一个数是否符合这样的限制,但是发现这样应该是m^2 * n^2的时间复杂度,因为需要遍历每个元素并且同时遍历当前行和列。但是根据观察发现,我们只需要每行的最小值以及每列的最大值,这样就想到可以先求其中一个然后看交集,如果存在则符合这样的要求。这样只需要遍历matrix每个元素一遍。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// time:O(mn) space:O(m)
// set intersection
public List<Integer> luckyNumbers (int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return new ArrayList<>();
HashSet<Integer> minOfRows = new HashSet<>();
for (int[] row : matrix) {
int min = row[0];
for (int n : row) {
min = Math.min(min, n);
}
minOfRows.add(min);
}
int m = matrix.length;
int n = matrix[0].length;
List<Integer> res = new ArrayList<>();
for (int j = 0; j < n; j++) {
int max = matrix[0][j];
for (int i = 0; i < m; i++) {
max = Math.max(max, matrix[i][j]);
}
if (minOfRows.contains(max)) res.add(max);
}
return res;
}