problem:2033. 获取单值网格的最小操作数
code
c++
class Solution {
public:
int minOperations(vector<vector<int>>& grid, int x) {
vector<int> q;
int cnt = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
q.push_back(grid[i][j]);
}
}
sort(q.begin(), q.end());
int len = q.size();
int mid = len >> 1;
int ans = 0;
for (auto item : q) {
if (item < q[mid]) {
if ((q[mid] - item) % x != 0)
return -1;
ans += (q[mid] - item)/x;
} else {
if((item-q[mid])%x!=0) return -1;
ans +=( item - q[mid])/x;
}
}
return ans;
}
};