Skip to content

Commit 38ea889

Browse files
committed
Add solution #302
1 parent dca7633 commit 38ea889

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,7 @@
290290
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|
291291
300|[Longest Increasing Subsequence](./solutions/0300-longest-increasing-subsequence.js)|Medium|
292292
301|[Remove Invalid Parentheses](./solutions/0301-remove-invalid-parentheses.js)|Hard|
293+
302|[Smallest Rectangle Enclosing Black Pixels](./solutions/0302-smallest-rectangle-enclosing-black-pixels.js)|Hard|
293294
303|[Range Sum Query - Immutable](./solutions/0303-range-sum-query-immutable.js)|Easy|
294295
304|[Range Sum Query 2D - Immutable](./solutions/0304-range-sum-query-2d-immutable.js)|Medium|
295296
306|[Additive Number](./solutions/0306-additive-number.js)|Medium|
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* 302. Smallest Rectangle Enclosing Black Pixels
3+
* https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/
4+
* Difficulty: Hard
5+
*
6+
* You are given an m x n binary matrix image where 0 represents a white pixel and 1 represents
7+
* a black pixel.
8+
*
9+
* The black pixels are connected (i.e., there is only one black region). Pixels are connected
10+
* horizontally and vertically.
11+
*
12+
* Given two integers x and y that represents the location of one of the black pixels, return
13+
* the area of the smallest (axis-aligned) rectangle that encloses all black pixels.
14+
*
15+
* You must write an algorithm with less than O(mn) runtime complexity
16+
*/
17+
18+
/**
19+
* @param {character[][]} image
20+
* @param {number} x
21+
* @param {number} y
22+
* @return {number}
23+
*/
24+
var minArea = function(image, x, y) {
25+
const rows = image.length;
26+
const cols = image[0].length;
27+
const top = binarySearch(0, x, true, true);
28+
const bottom = binarySearch(x, rows - 1, true, false);
29+
const left = binarySearch(0, y, false, true);
30+
const right = binarySearch(y, cols - 1, false, false);
31+
32+
return (bottom - top + 1) * (right - left + 1);
33+
34+
function binarySearch(start, end, isRow, isMin) {
35+
let result = isMin ? end : start;
36+
while (start <= end) {
37+
const mid = Math.floor((start + end) / 2);
38+
let hasBlack = false;
39+
for (let i = 0; i < (isRow ? cols : rows); i++) {
40+
const pixel = isRow ? image[mid][i] : image[i][mid];
41+
if (pixel === '1') {
42+
hasBlack = true;
43+
break;
44+
}
45+
}
46+
if (hasBlack) {
47+
result = mid;
48+
if (isMin) {
49+
end = mid - 1;
50+
} else {
51+
start = mid + 1;
52+
}
53+
} else {
54+
if (isMin) {
55+
start = mid + 1;
56+
} else {
57+
end = mid - 1;
58+
}
59+
}
60+
}
61+
return result;
62+
}
63+
};

0 commit comments

Comments
 (0)