leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit d200dac0fb0717dec93bfad66d467f7dccf1b049
parent e820af62f134a5cfd0a02b583d24207af3379b08
Author: Jack Sangdahl <jack@pngu.org>
Date:   Sat,  3 May 2025 01:12:52 -0600

1007. minimum domino rotations for equal row

Diffstat:
Amin_domino_rotation_eq_row.c | 40++++++++++++++++++++++++++++++++++++++++
Amin_domino_rotation_eq_row.py | 30++++++++++++++++++++++++++++++
2 files changed, 70 insertions(+), 0 deletions(-)

diff --git a/min_domino_rotation_eq_row.c b/min_domino_rotation_eq_row.c @@ -0,0 +1,40 @@ +// 1007. Minimum Domino Rotations For Equal Row +#include "leetcode.h" + +/* + * in a row of dominoes, 'tops[i]' and 'bottoms[i]' represents the top and + * bottom halves of the i'th domino. we may rotate the i'th domino so that + * 'tops[i]' and 'bottoms[i]' swap values. return the minimum number of + * rotations so that all values in 'tops' are the same, or all values in + * 'bottoms' are the same. if it cannot be done, return -1. + */ + +int minDominoRotations(int *tops, int topsSize, int *bottoms, int bottomsSize) { + int mask = 0x7E, num = -1, a = 0, b = 0; + for (int i = 0; i < topsSize; i++) { + mask &= ((1 << tops[i]) | (1 << bottoms[i])); + if (!mask) + return -1; + } + while (mask) { + num++; + mask >>= 1; + } + for (int i = 0; i < topsSize; i++) { + if (tops[i] == num) + a++; + if (bottoms[i] == num) + b++; + } + int max = a > b ? a : b; + return topsSize - max; +} + +int main() { + int t1[] = {2, 1, 2, 4, 2, 2}, b1[] = {5, 2, 6, 2, 3, 2}; + int t2[] = {3, 5, 1, 2, 3}, b2[] = {3, 6, 3, 3, 4}; + printf("%d\n", minDominoRotations(t1, ARRAY_SIZE(t1), b1, + ARRAY_SIZE(b1))); // expect: 2 + printf("%d\n", minDominoRotations(t2, ARRAY_SIZE(t2), b2, + ARRAY_SIZE(b2))); // expect: -1 +} diff --git a/min_domino_rotation_eq_row.py b/min_domino_rotation_eq_row.py @@ -0,0 +1,30 @@ +# 1007. Minimum Domino Rotations For Equal Row +from functools import reduce + +""" +in a row of dominoes, 'tops[i]' and 'bottoms[i]' represents the top and +bottom halves of the i'th domino. we may rotate the i'th domino so that +'tops[i]' and 'bottoms[i]' swap values. return the minimum number of +rotations so that all values in 'tops' are the same, or all values in +'bottoms' are the same. if it cannot be done, return -1. +""" + + +class Solution(object): + def minDominoRotations(self, tops, bottoms): + """ + :type tops: List[int] + :type bottoms: List[int] + :rtype: int + """ + s = reduce(set.__and__, (set(i) for i in zip(tops, bottoms))) + if not s: + return -1 + x = s.pop() + return min(len(tops) - tops.count(x), len(bottoms) - bottoms.count(x)) + + +if __name__ == "__main__": + obj = Solution() + print(obj.minDominoRotations(tops=[2, 1, 2, 4, 2, 2], bottoms=[5, 2, 6, 2, 3, 2])) + print(obj.minDominoRotations(tops=[3, 5, 1, 2, 3], bottoms=[3, 6, 3, 3, 4]))