ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

1007. Minimum Domino Rotations For Equal Row (M)

2020-10-19 21:32:39  阅读:281  来源: 互联网

标签:rotate int Domino Rotations Equal 瓷砖 values dominoes row


Minimum Domino Rotations For Equal Row (M)

题目

In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the ith 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.

Constraints:

  • 2 <= A.length == B.length <= 2 * 10^4
  • 1 <= A[i], B[i] <= 6

题意

给出若干个瓷砖的正反两面,判断能否通过翻转某些瓷砖来使所有瓷砖显示的数字相同,并求最小的翻转次数。

思路

可以从值域[1-6]入手,对于每一个数字,判断它是否出现在每一个瓷砖上,如果不是说明该情况不满足;如果是,计算最小翻转次数。


代码实现

Java

class Solution {
    public int minDominoRotations(int[] A, int[] B) {
        int ans = -1;
        for (int i = 1; i <= 6; i++) {
            boolean valid = true;
            int[] count = new int[2];
            for (int j = 0; j < A.length; j++) {
                if (A[j] != i && B[j] != i) {
                    valid = false;
                    break;
                }
                count[0] += A[j] == i ? 1 : 0;
                count[1] += B[j] == i ? 1 : 0;
            }
            if (valid) {
                int tmp = A.length - Math.max(count[0], count[1]);
                ans = ans == -1 ? tmp : Math.min(ans, tmp);
            }
        }
        return ans;
    }
}

标签:rotate,int,Domino,Rotations,Equal,瓷砖,values,dominoes,row
来源: https://www.cnblogs.com/mapoos/p/13843239.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有