日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【leetcode】1007. Minimum Domino Rotations For Equal Row

發布時間:2025/6/17 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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
  • 2 <= A.length == B.length <= 20000
  • 解題思路:因為?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的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。