53 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.

分析

题意:找到一组幸运数字,该数字在其行最小,在其列最大。

直接遍历是最简单的,有没有更优雅的方式?

评论区好像也是只有直接遍历的方法

遍历各行,拿到最小值
遍历各列,拿到最大值(遍历各行的同时其实也是在遍历各列)
如果行列同位置的值相等,则为幸运数字

解答

class Solution {
    public List<Integer> luckyNumbers (int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[] mi = new int[m];
        int[] mx = new int[n];
        // 初始化为无穷大,mx默认初始化全为0
        Arrays.fill(mi, Integer.MAX_VALUE);
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                mi[i] = Math.min(matrix[i][j], mi[i]);
                mx[j] = Math.max(matrix[i][j], mx[j]);
            }
        }
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (mi[i] == mx[j]) 
                    res.add(mi[i]);
        return res;        
    }
}
发布了118 篇原创文章 · 获赞 26 · 访问量 8007

猜你喜欢

转载自blog.csdn.net/weixin_43367550/article/details/104950916
53