Skip to content

Commit ff44462

Browse files
committed
feat[leetcode]:1380. Lucky Numbers in a Matrix
1 parent 7eef3d3 commit ff44462

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
*
3+
Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
4+
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
5+
6+
Example 1:
7+
8+
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
9+
Output: [15]
10+
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column
11+
Example 2:
12+
13+
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
14+
Output: [12]
15+
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
16+
Example 3:
17+
18+
Input: matrix = [[7,8],[1,2]]
19+
Output: [7]
20+
21+
22+
Constraints:
23+
24+
m == mat.length
25+
n == mat[i].length
26+
1 <= n, m <= 50
27+
1 <= matrix[i][j] <= 10^5.
28+
All elements in the matrix are distinct.} matrix
29+
30+
*/
31+
32+
33+
/**
34+
* @param {number[][]} matrix
35+
* @return {number[]}
36+
*/
37+
var luckyNumbers = function(matrix) {
38+
const column = matrix.length;
39+
const row = matrix[0].length;
40+
41+
for(let c = 0; c < column; c++){
42+
let minRow = Math.min(...matrix[c]);
43+
let pos = matrix[c].indexOf(minRow);
44+
45+
if(minRow === matrix[c][pos]){
46+
let tmpMaxRow = matrix[c][pos];
47+
for(let j = 0; j < column; j++){
48+
if(matrix[j][pos] > tmpMaxRow){
49+
tmpMaxRow = matrix[j][pos];
50+
break;
51+
}
52+
}
53+
if(tmpMaxRow === minRow){
54+
return [tmpMaxRow];
55+
}
56+
}
57+
}
58+
return []
59+
};
60+
61+
62+
63+
/**
64+
* 2020-03-15
65+
* Runtime: 56 ms, faster than 100.00% of JavaScript online submissions for Lucky Numbers in a Matrix.
66+
* Memory Usage: 35.3 MB, less than 100.00% of JavaScript online submissions for Lucky Numbers in a Matrix.
67+
*/

0 commit comments

Comments
 (0)