leetcode Daily Challenge on October 19th, 2020.
Difficulty : Medium
Related Topics : Array、Greedy
In a row of dominoes,
A[i]
andB[i]
represent the top and bottom halves of thei
th
domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)We may rotate the
i
th
domino, so thatA[i]
andB[i]
swap values.Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return
-1
.Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: 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.
Input: A = [3,5,1,2,3], B = [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.
- 2 <= A.length == B.length <= 2 * 10^4
- 1 <= A[i], B[i] <= 6
- mine
- Java
Runtime: 3 ms, faster than 98.43%, Memory Usage: 46.4 MB, less than 19.85% of Java online submissions
// O(N)time // O(1)space public int minDominoRotations(int[] A, int[] B) { int n = A.length; int res = -1; for(int i = 1; i < 7; i++){ int cA = 0, cB = 0; boolean stop = false; for(int j = 0; j < n; j++){ if(A[j] == i || B[j] == i){ if(A[j] != i){ cB++; }else if(B[j] != i){ cA++; } }else{ stop = true; break; } } if(stop) continue; if(res == -1) res = Math.min(cA, cB); else res = Math.min(res, Math.min(cA, cB)); } return res; }
- Java
- the most votes
Runtime: 5 ms, faster than 63.03%, Memory Usage: 46.1 MB, less than 19.85% of Java online submissions
// O(N)time // O(1)space public int minDominoRotations(int[] A, int[] B) { int[] countA = new int[7], countB = new int[7], same = new int[7]; int n = A.length; for (int i = 0; i < n; ++i) { countA[A[i]]++; countB[B[i]]++; if (A[i] == B[i]) same[A[i]]++; } for (int i = 1; i < 7; ++i) if (countA[i] + countB[i] - same[i] == n) return n - Math.max(countA[i], countB[i]); return -1; }
Runtime: 3 ms, faster than 98.43%, Memory Usage: 46.9 MB, less than 19.85% of Java online submissions
// O(N)time // O(1)space public int minDominoRotations(int[] A, int[] B) { int res = A.length+1; if(A[0] == B[0]){ res = Math.min(helper(A, B, 1, A[0]), helper(B, A, 1, A[0])); }else{ // use A[0] && rotate to A res = Math.min(res, helper(A, B, 1, A[0])); // use A[0] && rotate to B res = Math.min(res, 1+helper(B, A, 1, A[0])); // use B[0] && rotate to A res = Math.min(res, 1+helper(A, B, 1, B[0])); // use B[0] && rotate to B res = Math.min(res, helper(B, A, 1, B[0])); } return res > A.length ? -1 : res; } public int helper(int[] A, int[] B, int idx, int val){ int cnt = 0; for(int i=idx; i<A.length; i++){ if(A[i] == val) ; else if(B[i] != val) return A.length+1; else cnt++; } return cnt; }