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.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Solution {
6 public IList<int> LuckyNumbers (int[][] matrix) {
7 List<int> result = new List<int>();
8 int m = matrix.Length;
9 int n = matrix[0].Length;
10 int[] minRow = new int[m];
11
12 for (int i = 0; i < m; i++) {
13 minRow[i] = int.MaxValue;
14 for (int j = 0; j < n; j++) {
15 minRow[i] = Math.Min(minRow[i], matrix[i][j]);
16 }
17 }
18
19 for (int j = 0; j < n; j++) {
20 int maxCol = int.MinValue;
21 for (int i = 0; i < m; i++) {
22 maxCol = Math.Max(maxCol, matrix[i][j]);
23 }
24 for (int i = 0; i < m; i++) {
25 if (matrix[i][j] == maxCol && matrix[i][j] == minRow[i]) {
26 result.Add(matrix[i][j]);
27 }
28 }
29 }
30 return result;
31 }
32}
This C# method uses two nested loops to calculate row minima and column maxima. If there are matching values, they are appended to the results list.
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.