Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間7月前 (2025/05/03 11:24), 7月前編輯推噓1(100)
留言1則, 1人參與, 7月前最新討論串1413/1548 (看更多)
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
文章代碼(AID): #1e5OnP7p (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1e5OnP7p (Marginalman)