Image Smoother LeetCode solution in Java

1
/**
2
* Constant Space Solution. Using input array to store the average This solution can be modified to
3
* work if numbers are upto 2^16 - 1 (65,535).
4
*
5
* <p>Time Complexity: O(8*M*N + M*N) = O(M*N)
6
*
7
* <p>Space Complexity: O(1)
8
*
9
* <p>M = Number of rows. N = Number of columns.
10
*
11
* <p>Note: Similar to "289. Game of Life"
12
*/
13
class Solution {
14
private static final int[][] DIRS = {
15
{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}
16
};
17

18
public int[][] imageSmoother(int[][] img) {
19
if (img == null) {
20
throw new IllegalArgumentException("Input image is null");
21
}
22
if (img.length == 0 || img[0].length == 0) {
23
return img;
24
}
25

26
int rows = img.length;
27
int cols = img[0].length;
28
if (rows == 1 && cols == 1) {
29
return img;
30
}
31

32
for (int i = 0; i < rows; i++) {
33
for (int j = 0; j < cols; j++) {
34
int sum = img[i][j];
35
int count = 1;
36
for (int[] d : DIRS) {
37
int x = i + d[0];
38
int y = j + d[1];
39
if (x >= 0 && x < rows && y >= 0 && y < cols) {
40
sum += img[x][y] & 0xFF;
41
count++;
42
}
43
}
44
img[i][j] |= (sum / count) << 8;
45
}
46
}
47
for (int i = 0; i < rows; i++) {
48
for (int j = 0; j < cols; j++) {
49
img[i][j] >>>= 8;
50
}
51
}
52

53
return img;
54
}
55
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0