1
+ package medium
2
+
3
+ import ArraysTopic
4
+ import GreedyTopic
5
+
6
+ /* *
7
+ * 1007. Minimum Domino Rotations For Equal Row
8
+ * https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/
9
+ *
10
+ In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino.
11
+ (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
12
+ We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
13
+ 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.
14
+ If it cannot be done, return -1.
15
+ */
16
+
17
+ class Medium1007 : ArraysTopic , GreedyTopic {
18
+
19
+ fun minDominoRotations (tops : IntArray , bottoms : IntArray ): Int {
20
+ var result = Int .MAX_VALUE
21
+ for (i in 1 .. 6 ) {
22
+ var resTop = 0
23
+ var resBottom = 0
24
+ for (j in tops.indices) {
25
+ if (resTop >= 0 ) {
26
+ if (i != tops[j]) {
27
+ if (i != bottoms[j]) resTop = - 1 else resTop++
28
+ }
29
+ }
30
+ if (resBottom >= 0 ) {
31
+ if (i != bottoms[j]) {
32
+ if (i != tops[j]) resBottom = - 1 else resBottom++
33
+ }
34
+ }
35
+ if (resTop >= result && resBottom >= result) break
36
+ }
37
+ if (resTop >= 0 ) result = minOf(result, resTop)
38
+ if (resBottom >= 0 ) result = minOf(result, resBottom)
39
+ }
40
+ return if (result == Int .MAX_VALUE ) - 1 else result
41
+ }
42
+ }
43
+
44
+ fun main () {
45
+ println (Medium1007 ().minDominoRotations(intArrayOf(2 , 1 , 2 , 4 , 2 , 2 ), intArrayOf(5 , 2 , 6 , 2 , 3 , 2 )))
46
+ println (Medium1007 ().minDominoRotations(intArrayOf(3 , 5 , 1 , 2 , 3 ), intArrayOf(3 , 6 , 3 , 3 , 4 )))
47
+ println (Medium1007 ().minDominoRotations(intArrayOf(1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ), intArrayOf(1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 )))
48
+ }
0 commit comments