leetcode-矩阵中的幸运数

 题目是LeetCode第180场周赛的第一题,链接:矩阵中的幸运数。具体描述为:给你一个 m * n 的矩阵,矩阵中的数字各不相同 。请你按任意顺序返回矩阵中的所有幸运数。幸运数是指矩阵中满足同时下列两个条件的元素:

  • 在同一行的所有元素中最小
  • 在同一列的所有元素中最大

 示例1:

输入:matrix = [[3,7,8],[9,11,13],[15,16,17]]
输出:[15]
解释:15 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

 示例2:

输入:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
输出:[12]
解释:12 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

 示例3:

输入:matrix = [[7,8],[1,2]]
输出:[7]

 没啥好说的,直接遍历矩阵,先遍历每一行,记录每一行最小值所在位置,再遍历每一列,看最大值所在位置是否为其所在行的最小值。

 时间复杂度为 O ( M N ) O(MN) O(MN),空间复杂度为 O ( M N ) O(MN) O(MN)

 JAVA版代码如下:

class Solution {
    public List<Integer> luckyNumbers (int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        boolean[][] recordMin = new boolean[row][col];
        for (int i = 0; i < row; ++i) {
            int minJ = 0;
            for (int j = 1; j < col; ++j) {
                if (matrix[i][j] < matrix[i][minJ]) {
                    minJ = j;
                }
            }
            recordMin[i][minJ] = true;
        }
        List<Integer> result = new LinkedList<>();
        for (int j = 0; j < col; ++j) {
            int maxI = 0;
            for (int i = 1; i < row; ++i) {
                if (matrix[i][j] > matrix[maxI][j]) {
                    maxI = i;
                }
            }
            if (recordMin[maxI][j]) {
                result.add(matrix[maxI][j]);
            }
        }
        return result;
    }
}

 提交结果如下:


 Python版代码如下:

class Solution:
    def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
        row = len(matrix)
        col = len(matrix[0])
        recordMin = [[False for _ in range(col)] for _ in range(row)]
        result = []
        for i in range(row):
            minJ = 0
            for j in range(1, col):
                if matrix[i][j] < matrix[i][minJ]:
                    minJ = j
            recordMin[i][minJ] = True
        for j in range(col):
            maxI = 0
            for i in range(1, row):
                if matrix[i][j] > matrix[maxI][j]:
                    maxI = i
            if recordMin[maxI][j]:
                result.append(matrix[maxI][j])
        return result

 提交结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值