LeetCode 1337. The K Weakest Rows in a Matrix
考点 | 难度 |
---|---|
Sorting | Easy |
题目
You are given an m x n
binary matrix mat of 1’s (representing soldiers) and 0’s (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1’s will appear to the left of all the 0’s in each row.
A row i
is weaker than a row j
if one of the following is true:
· The number of soldiers in row i
is less than the number of soldiers in row j
.
· Both rows have the same number of soldiers and i < j
.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
思路
用binary search找到每一行的第一个0。用map根据每行的士兵个数排序。
答案
public int[] kWeakestRows(int[][] mat, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<mat.length; i++) {
map.put(i, getNumbersOfSoldiers(mat[i]));
}
// Sort map by value
List<Integer> list = new ArrayList<>(map.keySet());
Collections.sort(list, (a,b) -> map.get(a) - map.get(b));
return list.stream().limit(k).mapToInt(i -> i).toArray();
}
private int getNumbersOfSoldiers(int[] arr) {
int start = 0;
int end = arr.length - 1;
// Binary Search to find the first index of 0
while(start <= end) {
int mid = start + (end - start)/2;
if(arr[mid] == 0) {
end = mid-1;
} else {
start = mid+1;
}
}
return start;
}