Sponsored
Sponsored
This approach involves two main steps. First, find the minimum element in each row and keep track of the potential lucky numbers. Then, verify these potential numbers to check if they are the maximum in their respective columns.
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix.
Space Complexity: O(m) for storing the minimum indices for each row.
1var luckyNumbers = function(matrix) {
2 let minRow = matrix.map(row => Math.min(...row));
3 let maxCol = Array(matrix[0].length).fill(Number.MIN_SAFE_INTEGER);
4
5 for (let i = 0; i < matrix.length; i++) {
6 for (let j = 0; j < matrix[i].length; j++) {
7 maxCol[j] = Math.max(maxCol[j], matrix[i][j]);
8 }
9 }
10
11 return minRow.filter(val => maxCol.includes(val));
12};
The JavaScript solution uses a two-step approach to identify row minima across the entire row, then the maximum from the entire column.
This approach leverages set operations from mathematics to identify potential lucky numbers. We extract the row minimums and column maximums into separate sets and find the intersection of these sets for possible lucky numbers.
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns.
Space Complexity: O(n) for storing column maximums.
1using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<int> LuckyNumbersWithSet(int[][] matrix) {
HashSet<int> rowMinSet = new HashSet<int>();
foreach (var row in matrix) {
rowMinSet.Add(row.Min());
}
int[] colMax = new int[matrix[0].Length];
Array.Fill(colMax, int.MinValue);
for (int j = 0; j < matrix[0].Length; j++) {
for (int i = 0; i < matrix.Length; i++) {
colMax[j] = Math.Max(colMax[j], matrix[i][j]);
}
}
List<int> luckyNumbers = new List<int>();
foreach (int max in colMax) {
if (rowMinSet.Contains(max)) {
luckyNumbers.Add(max);
}
}
return luckyNumbers;
}
}
Set operations enable efficiently tracking minima and maxima in C#. The solution checks intersection occurrences to derive lucky numbers.