Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 1337. The K Weakest Rows in a Matrix #93

Open
Woodyiiiiiii opened this issue Mar 27, 2022 · 0 comments
Open

LeetCode 1337. The K Weakest Rows in a Matrix #93

Woodyiiiiiii opened this issue Mar 27, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

  1. 用优先队列排序
  2. 用双指针查找边界
class Solution {
    public int[] kWeakestRows(int[][] mat, int k) {

        int m = mat.length, n = mat[0].length;

        PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0]);

        for (int i = 0; i < m; ++i) {
            int l = 0, r = n - 1;
            while (l <= r) {
                int mid = l + (r - l) / 2;
                if (mat[i][mid] == 1) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
            pq.offer(new int[]{l, i});
        }

        int[] ans = new int[k];
        for (int i = 0; i < k; ++i) {
            if (!pq.isEmpty()) {
                int[] poll = pq.poll();
                ans[i] = poll[1];
            }
        }

        return ans;

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant