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.
1#include <stdio.h>
2#define MAX(a, b) ((a) > (b) ? (a) : (b))
3
4void luckyNumbers(int** mat, int matSize, int* matColSize, int* returnSize, int* returnArr){
5 int minRow[matSize];
6 for(int i = 0; i < matSize; i++){
7 minRow[i] = 0;
8 for(int j = 1; j < matColSize[i]; j++){
9 if(mat[i][j] < mat[i][minRow[i]]){
10 minRow[i] = j;
11 }
12 }
13 }
14
15 *returnSize = 0;
16 for(int j = 0; j < matColSize[0]; j++){
17 int isMax = 1;
18 int maxVal = mat[0][j];
19 for(int i = 0; i < matSize; i++){
20 if(mat[i][j] > maxVal){
21 maxVal = mat[i][j];
22 }
23 }
24 for(int i = 0; i < matSize; i++){
25 if(mat[i][j] == maxVal && j == minRow[i]){
26 returnArr[(*returnSize)++] = maxVal;
27 break;
28 }
29 }
30 }
31}
32
This C program identifies lucky numbers by first finding the index of the minimum in each row. Then it checks those values across columns to ascertain if they're maximums within their respective columns.
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.