LeetCode Lucky Numbers in a Matrix

1380. Lucky Numbers in a Matrix

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:

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

Example 2:

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.

Example 3:

Input: matrix = [[7,8],[1,2]]
Output: [7]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= n, m <= 50
  • 1 <= matrix[i][j] <= 10^5.
  • All elements in the matrix are distinct.

给定一个没有重复元素的矩阵,要求找出矩阵中的幸运数字,幸运数字的定义是它是所在行的最小值且是所在列的最大值。

有点意思的题目,如果暴力解法,遍历每个元素,同时判断它是否是所在行最小值且所在列最大值的话,时间复杂度高达$O((mn)^2)$,不可取。

更好的方法是,在遍历的过程中,记录当前行的最小值即当前列的最大值,最后判断一下最小值的数组和最大值的数组是否有相等元素,如果有的话,说明这个数是所在行的最小值且是所在列的最大值。可以这样做的原因是矩阵中没有重复元素。

完整代码如下:

class Solution {
public:
	vector<int> luckyNumbers(vector<vector<int>>& matrix) {
		vector<int> ans;
		int m = matrix.size(), n = matrix[0].size();
		vector<int> rowmin(m, INT_MAX), colmax(n, INT_MIN);
		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				rowmin[i] = min(rowmin[i], matrix[i][j]);
				colmax[j] = max(colmax[j], matrix[i][j]);
			}
		}
		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				if (rowmin[i] == colmax[j])ans.push_back(rowmin[i]);
			}
		}
		return ans;
	}
};

本代码提交AC,用时24MS。

Leave a Reply

Your email address will not be published. Required fields are marked *