Re: [閒聊] 每日leetcode
https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid
2033. Minimum Operations to Make a Uni-Value Grid
給你一個二維陣列和一個數字x,你每次可以對任意元素+x或-x,求出最少幾次操作可
以讓陣列數字相等,如果不能相等返回-1。
思路:
1.因為要全部數字相等,所以任意數字相減後一定被x整除,如果不整除直接返回。
2.越中間的數字越可能得到答案所以找出中位數的數字當作目標數字,把每個數字減去
中位數的數字除以x可以得到總操作數。
Java Code:
----------------------------------------
class Solution {
public int minOperations(int[][] grid, int x) {
List<Integer> list = new ArrayList<>();
int val = grid[0][0];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (Math.abs(grid[i][j] - val) % x != 0) {
return -1;
}
list.add(grid[i][j]);
}
}
if (list.size() == 1) {
return 0;
}
list.sort(Comparator.naturalOrder());
int n = list.size();
int mid = list.get(n/2);
int cost = 0;
for (int num : list) {
cost += Math.abs(mid - num) / x;
}
return cost;
}
}
----------------------------------------
寫了我40分鐘還吃了兩個WA 恨數學題 我還耍白癡去找了中間兩個數中間
的數來當目標 仔細想想更中間會要更多操作數 腦袋壞了
--
你跟我說這個我有什麼辦法
https://i.imgur.com/wb5zrOy.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.101.161 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1743006410.A.DA4.html
推
03/27 00:41,
8月前
, 1F
03/27 00:41, 1F
討論串 (同標題文章)
完整討論串 (本文為第 1373 之 1548 篇):