Lucky Numbers in a Matrix
给一个矩阵, 找出所有的lucky number. lucky number是指row中最小的, col中最大的. 这个题因为知道要满足这两个条件, 那么用set存一下所有满足第一个条件的值, 然后找第二个条件的值, 并且看看set中有没有这个数字即可.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public List<Integer> luckyNumbers (int[][] m) { List<Integer> res = new ArrayList<>(); Set<Integer> set = new HashSet<>(); for(int i = 0 ; i < m.length; i++) { int min = Integer.MAX_VALUE; for(int j = 0; j < m[0].length; j++) { min = Math.min(min, m[i][j]); } set.add(min); } for(int j = 0 ; j < m[0].length; j++) { int max = Integer.MIN_VALUE; for(int i = 0; i < m.length; i++) { max = Math.max(max, m[i][j]); } if(set.contains(max)) res.add(max); } return res; } } |