LeetCode 1380. 矩阵中的幸运数 Lucky Numbers in a Matrix

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

给你一个 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]
 

提示:

m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5
矩阵中的所有元素都是不同的

 

二、英文版

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

三、My answer

class Solution:
    def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
        res = []
        minnum_list = {}
#         找到每一行的最小值,存入字典,key是数字,value是该数字的下标
        for i in range(len(matrix)):
            # min_line = min(matrix[i])
            min_num = matrix[i][0]
            column = 0
            for j in range(len(matrix[i])):
                if matrix[i][j] < min_num:
                    min_num = matrix[i][j]
                    column = j
            minnum_list[min_num] = [i,column]
        
        print("minnum_list:",minnum_list)
        # 遍历字典
        flag = 0
        for key in minnum_list:
            max_col = minnum_list[key][1] # 找到对应列
            print("max_col:",max_col)
            #   遍历该列,判断 key 是否为最大值
            for row in range(len(matrix)):
                if matrix[row][max_col] > key:
                    flag = 1
                    break
            if flag == 0:
                res.append(key)
            else:
                flag = 0
                continue
        return res
"""
[[3,7,8],[9,11,13],[15,16,17]]
[[1,10,4,2],[9,3,8,7],[15,16,17,12]]
[[7,8],[1,2]]
  """                 
        
                    

四、解题报告

先找到每一行中的最小元素,再逐个比较这些最小元素所在的列中,该元素是不是列中的最大值。如果是,放入结果集。

你可能感兴趣的:(LeetCode\,LintCode,每周一题坑男友系列)