File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=2033 lang=cpp
3
+ *
4
+ * [2033] Minimum Operations to Make a Uni-Value Grid
5
+ */
6
+
7
+ // @lc code=start
8
+ #include " bits/stdc++.h"
9
+ using namespace std ;
10
+
11
+ class Solution {
12
+ public:
13
+ int minOperations (vector<vector<int >>& grid, int x) {
14
+ vector<int > nums;
15
+
16
+ for (auto & row : grid) {
17
+ for (int num : row) {
18
+ nums.push_back (num);
19
+ }
20
+ }
21
+
22
+ int base_mod = nums[0 ] % x;
23
+ for (int num : nums) {
24
+ if (num % x != base_mod) {
25
+ return -1 ; // 無法轉成相同數值
26
+ }
27
+ }
28
+
29
+ for (int & num : nums) {
30
+ num = (num - base_mod) / x; // 減掉餘數以後變成同一 base
31
+ }
32
+ sort (nums.begin (), nums.end ());
33
+
34
+ int median = nums[nums.size () / 2 ];
35
+ int operations = 0 ;
36
+ for (int num : nums) {
37
+ operations += abs (num - median);
38
+ }
39
+
40
+ return operations;
41
+ }
42
+ };
43
+ // @lc code=end
44
+
You can’t perform that action at this time.
0 commit comments