[LeetCode] 2033. Minimum Operations to Make a Uni-Value Grid

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.

Example 2:
Input: grid = [[1,5],[2,3]], x = 1
Output: 5
Explanation: We can make every element equal to 3.

Example 3:
Input: grid = [[1,2],[3,4]], x = 2
Output: -1
Explanation: It is impossible to make every element equal.

Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104

获取单值网格的最小操作数。

给你一个大小为 m x n 的二维整数网格 grid 和一个整数 x 。每一次操作,你可以对 grid 中的任一元素 加 x 或 减 x 。

一个 单值网格 是全部元素都相等的网格。

返回使网格化为单值网格所需的 最小 操作数。如果不能,返回 -1 。

思路

思路是先排序,然后用中位数比较。

具体实现是,把所有数字从 grid 里拿出来,放在一个一维数组里。然后把这个一维数组排序。然后遍历这个一维数组,把数组中每个数字arr[i]与数组的中位数mid比较。如果两者之间的差不能被 x 整除,那么返回 -1。否则,把两者之间的差除以 x 加到结果上。

复杂度

时间O(nlogn)
空间O(n)

代码

Java实现

class Solution {
    public int minOperations(int[][] grid, int x) {
        int m = grid.length;
        int n = grid[0].length;
        int[] arr = new int[m * n];
        int index = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                arr[index++] = grid[i][j];
            }
        }
        Arrays.sort(arr);
        int len = arr.length;
        int mid = arr[len / 2];

        int count = 0;
        for (int i = 0; i < len; i++) {
            int dis = Math.abs(mid - arr[i]);
            if (dis % x != 0) {
                return -1;
            }
            count += dis / x;
        }
        return count;
    }
}
posted @ 2025-03-27 02:15  CNoodle  阅读(32)  评论(0)    收藏  举报