You are given a 2D integer grid
of size m x n
and an integer x
. In one operation, you can add x
to or subtract x
from any element in the grid
.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1
.
Example 1:
Input: grid = [[2,4],[6,8]], x = 2 Output: 4 Explanation: We can make every element equal to 4 by doing the following: - Add x to 2 once. - Subtract x from 6 once. - Subtract x from 8 twice. A total of 4 operations were used.
思路:找到最小值,然后每个值跟最小值的差值,必须是x的倍数,否则return -1;同时,找到middian的数,然后最小的move就是所有元素和median的差值/x;
class Solution {
public int minOperations(int[][] grid, int x) {
int m = grid.length;
int n = grid[0].length;
int minvalue = Integer.MAX_VALUE;
List<Integer> list = new ArrayList<>();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
list.add(grid[i][j]);
minvalue = Math.min(minvalue, grid[i][j]);
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(( grid[i][j] - minvalue) % x != 0) {
return -1;
}
}
}
Collections.sort(list, (a, b) -> (a - b));
int middian = list.get(list.size() / 2);
int res = 0;
for(int i = 0; i < list.size(); i++) {
res += Math.abs(list.get(i) - middian) / x;
}
return res;
}
}