2033. Minimum Operations to Make a Uni-Value Grid - Medium

前往題目

想法

  • 中位數應該是最靠近所有數字的數

思路

  1. 把陣列扁平化,因為位置資訊不重要
  2. 扁平化後就可以排序並找到中位數
  3. 接著計算步數
  4. 只有當前數字減去中位數後,不能以每次x的步伐走到中位數才是invalid的狀況

Code

class Solution {
    public int minOperations(int[][] grid, int x) {
        int[] elements = new int[grid.length * grid[0].length];

        int index = 0;
        // Move the elements from the grid
        for (int i = 0; i < grid.length; ++i) {
            for (int j = 0; j < grid[0].length; ++j) {
                elements[index] = grid[i][j];
                ++index;
            }
        }

        // Sort it to find median
        Arrays.sort(elements);

        int median = elements[(elements.length - 1) / 2];
        int steps = 0;

        // Count steps
        for (int i = 0; i < elements.length; ++i) {
            // Skip the median itself
            if (elements[i] == median) continue;

            // Found invalid value
            if (Math.abs(elements[i] - median) % x != 0) {
                return -1;
            }

            // Update steps
            steps += Math.abs(elements[i] - median) / x;
        }

        return steps;
    }
}
JAVA

2033. Minimum Operations to Make a Uni-Value Grid - Medium
https://f88083.github.io/2025/03/26/2033-Minimum-Operations-to-Make-a-Uni-Value-Grid-Medium/
作者
Simon Lai
發布於
2025年3月26日
許可協議