Article Directory
1. Title
In a row of dominoes, A[i] and B[i] represent the upper and lower half of the i-th domino, respectively. (A domino is formed by tiling two numbers from 1 to 6 in the same column-there is a number on each half of the tile.)
We can rotate the i-th domino so that the values of A[i] and B[i] are swapped.
Can return all the values of A or B, all the values are the same minimum number of revolutions .
If it cannot be done, return -1.
Example 1:
输入:A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
输出:2
解释:
图一表示:在我们旋转之前, A 和 B 给出的多米诺牌。
如果我们旋转第二个和第四个多米诺骨牌,
我们可以使上面一行中的每个值都等于 2,如图二所示。
示例 2:
输入:A = [3,5,1,2,3], B = [3,6,3,3,4]
输出:-1
解释:
在这种情况下,不可能旋转多米诺牌使一行的值相等。
提示:
1 <= A[i], B[i] <= 6
2 <= A.length == B.length <= 20000
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/minimum-domino-rotations-for-equal-row The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
2. Problem solving
- Find the number x where the number >= n
- Check the two numbers in each position:
- All equal to x, no need to change, record times r2
- Not equal to x, not satisfying the meaning of the question
- One is equal to x, and the
answer to record the number of rotations r1 is min (r 1, n − r 2 − r 1) \min(r1, n-r2-r1)min ( r 1 ,n−r 2−r 1 )
class Solution {
public:
int minDominoRotations(vector<int>& A, vector<int>& B) {
int n = A.size();
vector<int> count(7, 0);
for(int i = 0; i < n; i++)
{
count[A[i]]++;//计数
count[B[i]]++;
}
int num = -1;
for(int i = 1; i <= 6; ++i)
{
if(count[i] >= n)//个数达标的数
num = i;
}
if(num == -1)
return -1;
int rotation = 0, notrotation = 0;
for(int i = 0; i < n; ++i)
{
if(A[i] == num && B[i] == num)
notrotation++;//两个都是,不需要交换
else if(A[i] != num && B[i] != num)
return -1;//都不等,不存在
else if(A[i] == num)
rotation++;
}
return min(rotation, n-notrotation-rotation);
}
};
304 ms 100.7 MB
My CSDN blog address https://michael.blog.csdn.net/
Long press or scan the QR code to follow my official account (Michael Amin), come on together, learn and make progress together!