Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

1007. Minimum Domino Rotations For Equal Row

In a row of dominoes, tops[i] and bottoms[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 tops[i] and bottoms[i] swap values.

Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.

If it cannot be done, return -1.

Example 1

1
2
3
4
5
6
7
8
9
start:
tops = [2,1,2,4,2,2]
bottems = [5,2,6,2,3,2]

after rotation
tops = [2,2,2,2,2,2]
bottems = [5,1,6,4,3,2]

output: 2

Example 2

1
2
3
4
5
6
tops = [3,5,1,2,3]
bottoms = [3,6,3,3,4]

can't hava [3,3,3,3,3,3] in tops or bottoms

output: -1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
TS: O(n), SC: O(n)  
class Solution {
public int minDominoRotations(int[] top, int[] bottom) {
int n = top.length;
int a = top[0], b = bottom[0]; // rotate from [0]
for(int i = 1 ; i < n ; i++) {
// mark number different from [0] to -1
if(a != top[i] && a != bottom[i])
a = -1;
if(b != top[i] && b != bottom[i])
b = -1;
// different from two head, -1
if(a == -1 && b == -1)
return -1;
}
if(a == -1) a=b;
// count swap number
int tswap = 0, bswap = 0;
for(int i = 0 ; i < n ; i++) {
if(a != top[i])
tswap++;

if(a != bottom[i])
bswap++;
}
return Math.min(tswap, bswap);
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels