|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * 1380. Lucky Numbers in a Matrix |
| 8 | + * |
| 9 | + * Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order. |
| 10 | + * A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] |
| 14 | + * Output: [15] |
| 15 | + * Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column |
| 16 | + * |
| 17 | + * Example 2: |
| 18 | + * Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]] |
| 19 | + * Output: [12] |
| 20 | + * Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column. |
| 21 | + * |
| 22 | + * Example 3: |
| 23 | + * Input: matrix = [[7,8],[1,2]] |
| 24 | + * Output: [7] |
| 25 | + * |
| 26 | + * Constraints: |
| 27 | + * m == mat.length |
| 28 | + * n == mat[i].length |
| 29 | + * 1 <= n, m <= 50 |
| 30 | + * 1 <= matrix[i][j] <= 10^5. |
| 31 | + * All elements in the matrix are distinct. |
| 32 | + * */ |
| 33 | +public class _1380 { |
| 34 | + public static class Solution1 { |
| 35 | + public List<Integer> luckyNumbers(int[][] matrix) { |
| 36 | + List<Integer> result = new ArrayList<>(); |
| 37 | + for (int i = 0; i < matrix.length; i++) { |
| 38 | + for (int j = 0; j < matrix[0].length; j++) { |
| 39 | + if (luckyInRow(matrix[i][j], matrix[i])) { |
| 40 | + if (luckyInColumn(matrix[i][j], matrix, j)) { |
| 41 | + result.add(matrix[i][j]); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + return result; |
| 47 | + } |
| 48 | + |
| 49 | + private boolean luckyInColumn(int number, int[][] matrix, int columnIndex) { |
| 50 | + for (int i = 0; i < matrix.length; i++) { |
| 51 | + if (number < matrix[i][columnIndex]) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + } |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + private boolean luckyInRow(int number, int[] row) { |
| 59 | + for (int num : row) { |
| 60 | + if (number > num) { |
| 61 | + return false; |
| 62 | + } |
| 63 | + } |
| 64 | + return true; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments