-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakeMatrixEqual.java
More file actions
51 lines (40 loc) · 1.22 KB
/
Copy pathMakeMatrixEqual.java
File metadata and controls
51 lines (40 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package array;
import java.util.Arrays;
public class MakeMatrixEqual {
public static void main(String[] args) {
int[][] arr = {
{ 3, 63, 42},
{ 18, 12, 12},
{ 15, 21, 18},
{ 33, 84, 24},
};
int k = 3;
int result = makeMatrixEqual(arr, k);
System.out.println(result);
}
static int makeMatrixEqual(int[][] a, int k) {
int n = a.length;
if (n == 0) return 0;
int m = a[0].length;
int total = n * m;
int[] arr = new int[total];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i * m + j] = a[i][j];
}
}
Arrays.sort(arr);
// for (int i = 0; i < total ; i++) {
// System.out.println(i + " " + arr[i] + " " + makeMatrixEqualHelper(b, b[i], k));
// }
int median = arr[total / 2];
return makeMatrixEqualHelper(arr, median, k);
}
static int makeMatrixEqualHelper(int[] arr, int toEqual, int numOfOperation) {
int count = 0;
for (int j : arr) {
count += Math.abs((j - toEqual) / numOfOperation);
}
return count;
}
}