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.
Example 1:
Input: mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
给一个矩阵,元素只有0 和 1,且 1 都在 0 的前面,
按元素和最小的行数排序,取出前k个行数。
思路:
因为最多100行,每行只有0和1元素,所以每行的和最多是100(n <= 100)。
可以建立一个数组,下标就是每行的和。
每个数组里保存 对应和 的行数,
最后遍历这个数组,依次取出前k个行数即可。
直接对每行求和,运行出来是6ms,可以从哪里改进。
注意每行有个重要的特征,那就是1一定出现在0的前面,
所以,求和也就是找1和0的分界线,可以用binary search。
//0ms
public int[] kWeakestRows(int[][] mat, int k) {
ArrayList<Integer>[] sum = new ArrayList[101];
int[] result = new int[k];
int cnt = 0;
for(int i = 0; i < mat.length; i ++) {
int[] row = mat[i];
//求每行的和
int left = 0, right = row.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if (row[mid] == 1) left = mid + 1;
else right = mid - 1;
}
if(sum[left] == null) sum[left] = new ArrayList<Integer>();
sum[left].add(i);
}
for(int i = 0; i < 101; i ++) {
if(sum[i] == null) continue;
for(int j = 0; j < sum[i].size(); j++) {
if(cnt >= k) return result;
result[cnt] = sum[i].get(j);
cnt ++;
}
}
return result;
}
二分查找优化矩阵求和
本文介绍了一种使用二分查找法优化矩阵求和的方法,针对特定类型的矩阵(元素仅包含0和1,且1位于0之前),通过快速定位1和0的分界线来高效计算每行的元素和,进而找出矩阵中最弱的k行。
389

被折叠的 条评论
为什么被折叠?



