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 2 3 4 5 6 7
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
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.
// time:O(mn) space:O(m) // set intersection public List<Integer> luckyNumbers(int[][] matrix){ if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) returnnew ArrayList<>(); HashSet<Integer> minOfRows = new HashSet<>(); for (int[] row : matrix) { int min = row[0]; for (int n : row) { min = Math.min(min, n); } minOfRows.add(min); } int m = matrix.length; int n = matrix[0].length; List<Integer> res = new ArrayList<>(); for (int j = 0; j < n; j++) { int max = matrix[0][j]; for (int i = 0; i < m; i++) { max = Math.max(max, matrix[i][j]); } if (minOfRows.contains(max)) res.add(max); } return res; }