当前位置:网站首页>Leetcode1380: lucky numbers in matrix
Leetcode1380: lucky numbers in matrix
2022-07-02 16:44:00 【Slow ploughing of stupid cattle】
Catalog
4. Are there multiple lucky numbers ?
1. Title Description
To give you one m * n Matrix , The number in the matrix Each are not identical . Please press arbitrarily Return all the lucky numbers in the matrix in order . Lucky number refers to the elements in the matrix that meet the following two conditions at the same time :
- The smallest of all elements in the same row
- The largest of all elements in the same column
Example 1:
Input :matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output :[15]
explain :15 Is the only lucky number , Because it is the smallest value in its row , It is also the maximum value in the column .
Example 2:
Input :matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output :[12]
explain :12 Is the only lucky number , Because it is the smallest value in its row , It is also the maximum value in the column .
Example 3:
Input :matrix = [[7,8],[1,2]]
Output :[7]
Tips :
m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5
All elements in the matrix are different
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
2. Problem solving analysis
Obviously , There is at most one lucky number in each line , At most, there is only one lucky number in each column .
The intuitive method is progressive scanning . Find the minimum value in the first row , Then confirm whether it is the maximum value of the column , If yes, it is a lucky number . Column by column scanning is also acceptable , The reason is the same .
Time complexity analysis
Make m and n Represents the number of rows and columns of input data respectively .
For each line , The time complexity to find the minimum value is , The time complexity of finding the maximum value in the column where the minimum value is located is
, Therefore, the processing time complexity of each row is
. All in all m That's ok , So the total time complexity is
.
therefore , If the number of rows is greater than the number of columns , It should be advantageous to scan by column .
Spatial complexity analysis
During the search , In addition to storing a row minimum 、 The column where the row minimum value is located and the column maximum value , No additional storage required , So the space complexity is constant complexity .
3. Code implementation
class Solution:
def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix) # number of row
n = len(matrix[0]) # number of col
rslt = []
for k in range(m): # Iteration over each row
# Find row min and also the min index
# rowmin,minidx = self.findMin(matrix[k])
rowmin = matrix[k][0]
rowminidx = 0
for col in range(1,n):
if matrix[k][col] < rowmin:
rowmin = matrix[k][col]
rowminidx = col
# Find the max of column[minidx]
colmax = matrix[0][rowminidx]
for k in range(1,m):
if matrix[k][rowminidx] > colmax:
colmax = matrix[k][rowminidx]
# Whether the row-min coincidence with col-max
if colmax == rowmin:
rslt.append(colmax)
return rslt
if __name__ == '__main__':
sln = Solution()
matrix = [[3,7,8],[9,11,13],[15,16,17]]
print(sln.luckyNumbers(matrix))
matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
print(sln.luckyNumbers(matrix))
matrix = [[7,8],[1,2]]
print(sln.luckyNumbers(matrix))
matrix = [[7]] # corner case
print(sln.luckyNumbers(matrix))
matrix = [[8,7],[1,9]]
print(sln.luckyNumbers(matrix))
however , The above solution may be a little naive^-^. stay Leetcode The performance in submission is relatively poor :
# ======================================================================
# Execution time :96 ms, In all Python3 Defeated in submission 5.16% Users of
# Memory consumption :32.4 MB, In all Python3 Defeated in submission 5.16% Users of
# ======================================================================
Further efforts are needed .
4. Are there multiple lucky numbers ?
The Title Description implies that there may be multiple lucky numbers . But I want to design such a testcase When , It seems impossible to build such testcase Come on . I thought it over , It is believed that there should be no multiple lucky numbers that meet the requirements of this question .
Prove the following : Reduction to absurdity .
It's not general , hypothesis A[0][0] A lucky number , be A[0][0] Is the minimum value of the first line , meanwhile A[0][0] Is the maximum value of the first column . Suppose there is another number A[i][j](i>0, j>0), It's also a lucky number , By definition ,A[i][j] For the first time (i+1) The minimum value of the row , So I must be satisfied A[i][j]<A[0][j]<A[0][0]<A[0][j], This is related to A[i][j] It's a lucky number ( Column maximum ) The conclusion of is contradictory . Therefore, there cannot be more than one lucky number .
Based on this , The above program can be slightly optimized . That is, you can quit in advance after finding a lucky number .
边栏推荐
- SSM整合-异常处理器及项目异常处理方案
- Cloud native cicd framework: Tekton
- Yyds dry inventory uses thread safe two-way linked list to realize simple LRU cache simulation
- Rock PI Development Notes (II): start with rock PI 4B plus (based on Ruixing micro rk3399) board and make system operation
- July 1st gift: Yi Jingjie's "hundred day battle" ended perfectly, and the database of Guiyang bank was sealed in advance
- Remove the underline in router link
- TypeScript数组乱序输出
- 云原生的 CICD 框架:Tekton
- Foreign enterprise executives, continuous entrepreneurs, yoga and skiing masters, and a program life of continuous iteration and reconstruction
- [fluent] dart data type list set type (define set | initialize | generic usage | add elements after initialization | set generation function | set traversal)
猜你喜欢
数学分析_笔记_第6章:一元函数的Riemann积分
MySQL min() finds the minimum value under certain conditions, and there are multiple results
[North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array
[fluent] dart data type string type (string definition | string splicing | string API call)
电脑设备打印机驱动安装失败如何解决
What if the win11 app store cannot load the page? Win11 store cannot load page
How to use stustr function in Oracle view
Yolov5 practice: teach object detection by hand
unity Hub 登錄框變得很窄 無法登錄
Practice of traffic recording and playback in vivo
随机推荐
SSM整合-异常处理器及项目异常处理方案
Bib | graph representation based on heterogeneous information network learning to predict drug disease association
Thinking about absolute truth and relative truth
自注意力机制和全连接的图卷积网络(GCN)有什么区别联系?
day4
Unity使用UGUI设置一个简单多级水平方向下拉菜单(不需要代码)
False summer vacation
Hard core! One configuration center for 8 classes!
According to the atlas of data security products and services issued by the China Academy of information technology, meichuang technology has achieved full coverage of four major sectors
Global and Chinese markets for airport baggage claim conveyors 2022-2028: technology, participants, trends, market size and share Research Report
Global and Chinese market of oil analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
618 deep resumption: Haier Zhijia's winning methodology
sim2real环境配置教程
LeetCode 6. Z 字形变换 (N字形变换)
LeetCode 3. Longest substring without duplicate characters
Mysql database mysqldump why there is no statement to create a database
Everyone Xinfu builds: a one-stop intelligent business credit service platform
Sim2real environment configuration tutorial
PCL least median square method fitting plane
Today in history: Alipay launched barcode payment; The father of time-sharing system was born; The first TV advertisement in the world