题目
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);
}
}