forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2033.java
32 lines (30 loc) · 943 Bytes
/
_2033.java
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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class _2033 {
public static class Solution1 {
public int minOperations(int[][] grid, int x) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
list.add(grid[i][j]);
}
}
if (list.size() <= 1) {
return 0;
}
Collections.sort(list);
int median = list.get(list.size() / 2);
int ops = 0;
for (int i = 0; i < list.size(); i++) {
int diff = Math.abs(list.get(i) - median);
if (diff % x != 0) {
return -1;
}
ops += diff;
}
return ops / x;
}
}
}