Re: [閒聊] 每日LeetCode

看板Marginalman作者 (みけねこ的鼻屎)時間2年前 (2023/09/18 17:10), 編輯推噓1(100)
留言1則, 1人參與, 2年前最新討論串413/719 (看更多)
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/description 1337. The K Weakest Rows in a Matrix 給你一個陣列mat[][],mat[i][j] = 0 表示市民,1 表示士兵,給予一個數字 k ,如果一個列的士兵越少這個列的守備越薄弱,如果士兵一樣多比較上面的列更 薄弱,求出前 k 個守備薄弱的列。 思路: 1.用一個 Heap 儲存每一列的士兵數量和列編號,依照題目要求排序。 2.從 Heap 取出 k 個元素,把他們的編號返回即可。 Java Code: --------------------------------------------------- class Solution { public int[] kWeakestRows(int[][] mat, int k) { PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); for (int i = 0; i < mat.length; i++) { int count = 0; for (int j = 0; j < mat[0].length; j++) { count += mat[i][j] == 0 ? 0 : 1; } heap.offer(new int[]{count, i}); } int[] res = new int[k]; for (int i = 0; i < k; i++) { res[i] = heap.poll()[1]; } return res; } } --------------------------------------------------- -- https://i.imgur.com/4nfnn6f.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1695028202.A.761.html

09/18 17:11, 2年前 , 1F
你好猛喔 每天都寫一題
09/18 17:11, 1F
文章代碼(AID): #1b21FgTX (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1b21FgTX (Marginalman)