LeetCode 1007. Minimum Domino Rotations For Equal Row

混江龙づ霸主 提交于 2020-01-16 02:46:21

原题链接在这里:https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/

题目:

In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-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 that A[i] and B[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.

Example 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.

Example 2:

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.

Note:

  1. 1 <= A[i], B[i] <= 6
  2. 2 <= A.length == B.length <= 20000

题解:

Could make equal with A[0] or B[0].

To make equal with A[0], the loop condition is A[i] == A[0] || B[i] == A[0].

We could make A equal or B equal  to A[0]. If A[i] != A[0], there is swap on A to make A equal to A[0]. If B[i] != A[0], there is a swap on B to make B equal to A[0].

If index could come to the end, return the minimum of count of A swap and count of B swap.

Time Complexity: O(n).

Space: O(1).

AC Java:

 1 class Solution {
 2     public int minDominoRotations(int[] A, int[] B) {
 3         if(A == null || A.length == 0 || B == null || B.length == 0){
 4             return 0;
 5         }
 6         
 7         int n = A.length;
 8         for(int i = 0, a = 0, b = 0; i < n && (A[i] == A[0] || B[i] == A[0]); i++){
 9             if(A[i] != A[0]){
10                 a++;
11             }
12             
13             if(B[i] != A[0]){
14                 b++;
15             }
16             
17             if(i == n - 1){
18                 return Math.min(a, b);
19             }
20         }
21         
22         for(int i = 0, a = 0, b = 0; i < n && (A[i] == B[0] || B[i] == B[0]); i++){
23             if(A[i] != B[0]){
24                 a++;
25             }
26             
27             if(B[i] != B[0]){
28                 b++;
29             }
30             
31             if(i == n - 1){
32                 return Math.min(a, b);
33             }
34         }
35         
36         return -1;
37     }
38 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!