【leetcode】1007. Minimum Domino Rotations For Equal Row
題目如下:
In a row of dominoes,?A[i]?and?B[i]?represent the top and bottom halves of the?i-th domino.? (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the?i-th domino, so that?A[i]?and?B[i]?swap values.
Return the minimum number of rotations so that all the values in?A?are the same, or all the values in?B?are the same.
If it cannot be done, return?-1.
?
Example 1:
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.Example 2:
Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal.?
Note:
解題思路:因為?1 <= A[i], B[i] <= 6,所以如果能使得A或者B中所有元素的值一樣,那么就只有12種情況,即A中元素或者B中元素全為1/2/3/4/5/6,依次判斷這6種情況即可,如假設變換后A中元素全為1,從頭遍歷A與B,如果A[i] != 1 并且B[i] != 1表示無法使得A中元素全為1,繼續判斷2的情況;否則如果A[i] != 1 并且B[i] = 1,那么交換的次數加1;同理可求得B中元素也全為1的交換次數。遍歷完這6種情況后,如果無法滿足則返回-1,可以的話返回交換的最小值。
代碼如下:
class Solution(object):def minDominoRotations(self, A, B):""":type A: List[int]:type B: List[int]:rtype: int"""res = 20001for i in range(1,7):a_move = 0b_move = 0a_flag = Trueb_flag = Truefor j in range(len(A)):if A[j] != i:if B[j] != i:a_flag = Falseelse:a_move += 1if B[j] != i:if A[j] != i:b_flag = Falseelse:b_move += 1if a_flag == False and b_flag == False:breakif a_flag:res = min(res,a_move)if b_flag:res = min(res,b_move)return res if res != 20001 else -1?
轉載于:https://www.cnblogs.com/seyjs/p/10508861.html
總結
以上是生活随笔為你收集整理的【leetcode】1007. Minimum Domino Rotations For Equal Row的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JPress v2.0-rc.5 发布,
- 下一篇: 关于 Workbench中 pk,nn,