首页 > 其他 > 详细

LeetCode 1007. Minimum Domino Rotations For Equal Row

时间:2020-01-16 09:30:21      阅读:76      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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 }

LeetCode 1007. Minimum Domino Rotations For Equal Row

原文:https://www.cnblogs.com/Dylan-Java-NYC/p/12199439.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!