Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

 

Example 1:

Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column
Example 2:

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 3:

Input: matrix = [[7,8],[1,2]]
Output: [7]
 

Constraints:

m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5.
All elements in the matrix are distinct.

这题也直接按照题意来遍历矩阵就行了。

class LuckyNumbersInAMatrix : public Solution {
public:
    void Exec() {

    }
    vector<int> luckyNumbers (vector<vector<int>>& matrix) {
        vector<int> res;
        for (int row = 0; row < matrix.size(); row++) {
            int luckyNumber = 1e6;
            int index = 0;
            for (int col = 0; col < matrix[row].size(); col++) {
                if (matrix[row][col] < luckyNumber) {
                    luckyNumber = matrix[row][col];
                    index = col;
                }
            }
            bool match = true;
            for (int row = 0; row < matrix.size(); row++) {
                if (luckyNumber < matrix[row][index]) {
                    match = false;
                    break;
                }
            }
            if (match) {
                res.push_back(luckyNumber);
            }
        }
        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day