日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【leetcode】1007. Minimum Domino Rotations For Equal Row

發布時間:2025/6/17 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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的全部內容,希望文章能夠幫你解決所遇到的問題。

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