Leetcode 1007 Minimum Domino Rotations For Equal Row

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 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 * 104
1 <= A[i], B[i] <= 6

思路

如果最后能够rotate到一行中数字一样,说明每列中都会包含这个一样的数字。所以一共就需要考虑两种情况,都等于第一列的第一个数或是都等于第一列的第二个数。helper function就是有了这个target之后,遍历A,B中一行target出现的频次,如果有一列这个数AB中都没有,说明怎么换都不可能达成该target,直接返回-1。另外一个需要注意的地方就是if (A[i] == B[i]) continue;这句是必须的,考虑例子
A = [1, 2, 1, 2, 2]
B = [2, 1, 2, 2, 2]
如果不加的话数1是不可行的返回-1,对于数2最后两个2其实不用做交换,所以continue不加以计数。

代码

class Solution {
    
    public int minDominoRotations(int[] A, int[] B) {
        int t1 = helper(A, B, A[0]);
        int t2 = helper(A, B, B[0]);
        if (t1 == -1) return t2;
        if (t2 == -1) return t1;
        return Math.min(t1, t2);
    }
    
    public int helper(int[] A, int[] B, int target) {
        int countA = 0, countB = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i] != target && B[i] != target) {
                return -1;
            }
            if (A[i] == B[i]) continue;
            if (A[i] == target) {
                countA++;
            } else {
                countB++;
            }
        }
        return Math.min(countA, countB);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值