leetcode 1337. The K Weakest Rows in a Matrix(矩阵中最弱的K行)

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值