1337. 矩阵中战斗力最弱的 K 行

优先队列

import java.util.Comparator;
import java.util.PriorityQueue;

class Solution {
    public int[] kWeakestRows(int[][] mat, int k) {

        /**
         * 使用优先队列
         * 如果两行的和不同,按照和的大小顺序存储;如果相同,按照行的索引的大小存储
         */
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {

                if (o1[0] == o2[0]){
                    return o1[1] - o2[1];
                }

                return o1[0] - o2[0];
            }
        });

        for (int i = 0; i < mat.length; i++) {

            int sum = 0;

            for (int j = 0; j < mat[0].length; j++) {
                sum += mat[i][j];
            }

            pq.add(new int[]{sum, i});
        }

        int[] res = new int[k];

        for (int i = 0; i < res.length; i++) {
            res[i] = pq.poll()[1];
        }
        
        return res;
    }
}

/**
 * 时间复杂度 O(nlogn)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix/

posted @ 2021-11-01 21:06  振袖秋枫问红叶  阅读(37)  评论(0)    收藏  举报