Re: [閒聊] 每日leetcode
https://leetcode.com/problems/minimum-domino-rotations-for-equal-row
1007. Minimum Domino Rotations For Equal Row
有一種只有兩面的骰子數字可能是1~6,我們把他放在桌上,你可以翻轉骰子,找出
最少要翻轉幾次才可以讓骰子的底部或頂部數字都相同,如果不能就返回-1。
思路:
1.窮舉讓頂部和底部都是[1:6]共需要花多少翻轉次數,花至多O(n)時間就可以完成,
如果可以讓某個數字全部相同就取最少翻轉次數。
java code:
---------------------------------------------
class Solution {
public int minDominoRotations(int[] tops, int[] bottoms) {
int res = Integer.MAX_VALUE;
int n = tops.length;
for (int i = 1; i <= 6; i++) {
int topsCost = 0;
for (int j = 0; j < n; j++) {
if (tops[j] != i) {
if (bottoms[j] != i) {
topsCost = Integer.MAX_VALUE;
break;
} else {
topsCost++;
}
}
}
res = Math.min(res, topsCost);
int bottomsCost = 0;
for (int j = 0; j < n; j++) {
if (bottoms[j] != i) {
if (tops[j] != i) {
bottomsCost = Integer.MAX_VALUE;
break;
} else {
bottomsCost++;
}
}
}
res = Math.min(res, bottomsCost);
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}
---------------------------------------------
--
https://i.imgur.com/yRXNquY.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.104.111 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1746242649.A.1F3.html
※ 編輯: Rushia (49.159.104.111 臺灣), 05/03/2025 11:24:30
推
05/03 11:31,
7月前
, 1F
05/03 11:31, 1F
討論串 (同標題文章)
完整討論串 (本文為第 1413 之 1548 篇):