题目
https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix/
答案
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < mat.length;i++) {
int count = 0;
for (int num : mat[i]) {
if (num == 0) {
break;
}
count++;
}
map.computeIfAbsent(count, list -> new ArrayList<>()).add(i);
}
List<Integer> list = new ArrayList<>();
map.keySet().stream().sorted().forEach(row -> {
if (list.size() == k) {
return;
}
List<Integer> rows = map.get(row);
Collections.sort(rows);
int remaind = k-list.size();
for (int i = 0; i < Math.min(remaind, rows.size()); i++) {
list.add(rows.get(i));
}
});
int[] arr = new int[k];
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
return arr;
}
}
总结
简单题一遍过。还是数据结构的考察。
|