LeetCode 1380. Lucky Numbers in a Matrix矩陣中的幸運數【Easy】【Python】【暴力】
LeetCodepython
Given a m * n
matrix of distinct numbers, return all lucky numbers in the matrix in any order.git
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.github
Example 1:app
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:code
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:ip
Input: matrix = [[7,8],[1,2]] Output: [7]
Constraints:element
m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5
.力扣leetcode
給你一個 m * n 的矩陣,矩陣中的數字 各不相同 。請你按 任意 順序返回矩陣中的全部幸運數。get
幸運數是指矩陣中知足同時下列兩個條件的元素:it
示例 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
暴力
找出每一行的最小值,再判斷是不是當前列的最大值。
時間複雜度: O(m*n),m 是 matrix 的行數,n 是 matrix 的列數。
from typing import List class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: # solution one m, n = len(matrix), len(matrix[0]) flag = 0 res = [] for i in range(m): min_ = max_ = matrix[i][0] for j in range(n): if matrix[i][j] < min_: flag = j min_ = matrix[i][j] max_ = min_ for x in range(m): if matrix[x][flag] > max_: break elif x == m - 1: res.append(max_) return res
分別找出每一行的最小值和每一列的最大值,再判斷是否相等。
時間複雜度: O(max(m, n)),m 是 matrix 的行數,n 是 matrix 的列數。
from typing import List class Solution: def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: # solution two min_ = {min(rows) for rows in matrix} max_ = {max(columns) for columns in zip(*matrix)} # zip(*) 對矩陣進行轉置,即找出每一列中的最大值 return list(min_ & max_)