LeetCode知识点总结 - 133

LeetCode 1337. The K Weakest Rows in a Matrix

考点难度
SortingEasy
题目

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值