1007. Minimum Domino Rotations For Equal Row

Last updated

Last updated
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.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.int minDominoRotations(vector<int>& A, vector<int>& B) { // time: O(n); space: O(1)
if (A.size() != B.size()) return -1;
int n = A.size();
// A[0]
for (int i = 0, a = 0, b = 0; i < n && (A[i] == A[0] || B[i] == A[0]); ++i) {
if (A[i] != A[0]) ++a;
if (B[i] != A[0]) ++b;
if (i == n - 1) return min(a, b);
}
// B[0]
for (int i = 0, a = 0, b = 0; i < n && (A[i] == B[0] || B[i] == B[0]); ++i) {
if (A[i] != B[0]) ++a;
if (B[i] != B[0]) ++b;
if (i == n - 1) return min(a, b);
}
return -1;
}int minDominoRotations(vector<int>& A, vector<int>& B) { // time: O(n); space: O(1)
if (A.size() != B.size()) return -1;
vector<int> countA(6, 0), countB(6, 0), same(6, 0);
int n = A.size();
for (int i = 0; i < n; ++i) {
++countA[A[i] - 1];
++countB[B[i] - 1];
if (A[i] == B[i]) ++same[A[i] - 1];
}
for (int i = 0; i < 6; ++i) {
if (countA[i] + countB[i] - same[i] == n) return n - max(countA[i], countB[i]);
}
return -1;
}