1049 Minimum Domino Rotations For Equal Row
1049 Minimum Domino Rotations For Equal Row
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
**Input:** tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: 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.
Example 2:
1
2
3
4
5
6
**Input:** tops = [3,5,1,2,3], bottoms = [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.
Constraints:
1
2
3
2 <= tops.length <= 2 * 104
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::collections::HashMap;
use std::cmp::max;
use std::cmp::min;
impl Solution {
pub fn min_domino_rotations(tops: Vec<i32>, bottoms: Vec<i32>) -> i32 {
let mut dominoes = HashMap::new();
let mut dominoes_tops = HashMap::new();
let mut dominoes_bottoms = HashMap::new();
for (top, bottom) in tops.iter().zip(bottoms.iter()) {
if top == bottom {
*dominoes.entry(*top).or_insert(0) += 1;
// skip adding to tops or bottoms individually
} else {
*dominoes.entry(*top).or_insert(0) += 1;
*dominoes.entry(*bottom).or_insert(0) += 1;
*dominoes_tops.entry(*top).or_insert(0) += 1;
*dominoes_bottoms.entry(*bottom).or_insert(0) += 1;
}
}
let mut mx_k = 0;
let mut mx_v = 0;
for (k, v) in &dominoes {
if *v > mx_v {
mx_v = *v;
mx_k = *k;
}
}
let top_count = *dominoes_tops.get(&mx_k).unwrap_or(&0);
let bottom_count = *dominoes_bottoms.get(&mx_k).unwrap_or(&0);
println!("dominoes_tops: {:?}", dominoes_tops);
println!("dominoes_bottoms: {:?}", dominoes_bottoms);
println!("dominoes (combined): {:?}", dominoes);
println!("Max key: {}, Top count: {}, Bottom count: {}", mx_k, top_count, bottom_count);
if *dominoes.get(&mx_k).unwrap_or(&0) < (tops.len()) {
return -1
}
return min(top_count as i32 , bottom_count as i32);
}
}
This post is licensed under CC BY 4.0 by the author.
