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 <vector>
2#include <algorithm>
3
4std::vector<int> luckyNumbers (std::vector<std::vector<int>>& matrix) {
5 std::vector<int> result;
6 std::vector<int> rowMin;
7 std::vector<bool> colMax(matrix[0].size(), true);
8
9 for (const auto& row : matrix) {
10 rowMin.push_back(*std::min_element(row.begin(), row.end()));
11 }
12
13 for (int j = 0; j < matrix[0].size(); ++j) {
14 int max_in_col = matrix[0][j];
15 for (int i = 0; i < matrix.size(); ++i) {
16 max_in_col = std::max(max_in_col, matrix[i][j]);
17 }
18 for (int i = 0; i < matrix.size(); ++i) {
19 if (matrix[i][j] == max_in_col && matrix[i][j] == rowMin[i]) {
20 result.push_back(matrix[i][j]);
21 }
22 }
23 }
24
25 return result;
26}
In this C++ solution, we use a vector to store the minimum of each row. Then, for each column, we determine the maximum value and check if it matches any of the stored row minimums.
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.
1
We utilize Python's powerful collection tools to directly find intersections between row minima and column maxima, yielding possible lucky numbers efficiently.