Skip to content

Commit b9c069e

Browse files
authored
Create 1337-the-k-weakest-rows-in-a-matrix.js
1 parent 6756d84 commit b9c069e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* @param {number[][]} mat
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
const kWeakestRows = function(mat, k) {
7+
const pq = new PriorityQueue((a, b) => a[0] === b[0] ? a[1] > b[1] : a[0] > b[0])
8+
const res = [], m = mat.length
9+
for(let i = 0; i < m; i++) {
10+
pq.push([oneNum(mat[i]), i])
11+
if(pq.size() > k) pq.pop()
12+
}
13+
while(k > 0) res[--k] = pq.pop()[1]
14+
return res
15+
};
16+
17+
function oneNum(arr) {
18+
let l = 0, h = arr.length
19+
while(l < h) {
20+
const mid = l + ((h - l) >> 1)
21+
if(arr[mid] === 1) l = mid + 1
22+
else h = mid
23+
}
24+
return l
25+
}
26+
27+
28+
class PriorityQueue {
29+
constructor(comparator = (a, b) => a > b) {
30+
this.heap = []
31+
this.top = 0
32+
this.comparator = comparator
33+
}
34+
size() {
35+
return this.heap.length
36+
}
37+
isEmpty() {
38+
return this.size() === 0
39+
}
40+
peek() {
41+
return this.heap[this.top]
42+
}
43+
push(...values) {
44+
values.forEach((value) => {
45+
this.heap.push(value)
46+
this.siftUp()
47+
})
48+
return this.size()
49+
}
50+
pop() {
51+
const poppedValue = this.peek()
52+
const bottom = this.size() - 1
53+
if (bottom > this.top) {
54+
this.swap(this.top, bottom)
55+
}
56+
this.heap.pop()
57+
this.siftDown()
58+
return poppedValue
59+
}
60+
replace(value) {
61+
const replacedValue = this.peek()
62+
this.heap[this.top] = value
63+
this.siftDown()
64+
return replacedValue
65+
}
66+
67+
parent = (i) => ((i + 1) >>> 1) - 1
68+
left = (i) => (i << 1) + 1
69+
right = (i) => (i + 1) << 1
70+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
71+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
72+
siftUp = () => {
73+
let node = this.size() - 1
74+
while (node > this.top && this.greater(node, this.parent(node))) {
75+
this.swap(node, this.parent(node))
76+
node = this.parent(node)
77+
}
78+
}
79+
siftDown = () => {
80+
let node = this.top
81+
while (
82+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
83+
(this.right(node) < this.size() && this.greater(this.right(node), node))
84+
) {
85+
let maxChild =
86+
this.right(node) < this.size() &&
87+
this.greater(this.right(node), this.left(node))
88+
? this.right(node)
89+
: this.left(node)
90+
this.swap(node, maxChild)
91+
node = maxChild
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)