Leetcode 1007) Minimum Domino Rotations For Equal Row

image

class Solution {
    public int minDominoRotations(int[] tops, int[] bottoms) {
        //일단 6개 이상 있는 수를 조사한다. 없으면 걍 -1 리턴
        int[] domino = new int[6];
        for(int i =0;i<tops.length;i++){
            domino[tops[i]-1]+=1;
            domino[bottoms[i]-1]+=1;
        }
        int min=Integer.MAX_VALUE;
        int possible =-1;
        for(int i =0;i<6;i++){
            if(domino[i]>=tops.length){
                possible=i+1;
                int result1=0; int result2=0;
                for(int k=0;k<tops.length;k++){
                    if(tops[k]!=possible){
                        if(bottoms[k]==possible){
                            result1++;
                        }else{
                            result1=tops.length;
                            break;
                        }
                    }
                }
                for(int k=0;k<tops.length;k++){
                    if(bottoms[k]!=possible){
                        if(tops[k]==possible){
                            result2++;
                        }else{    
                            result2=tops.length;
                            break;
                        }
                    }
                }

                int tmp =Math.min(result1,result2);
                min = Math.min(tmp,min);
            }
        }
        if(min==tops.length || min ==Integer.MAX_VALUE){
            return -1;
        }

        return min;        
    }
}

다른 답안

class Solution {
    public int minDominoRotations(int[] A, int[] B) {
        int ans = -1;        
        for (int val = 1; val <= 6; val++) {
            int currAns = helper(A, B, val);

            if (currAns != -1 && (ans == -1 || ans > currAns)) {
                ans = currAns;
            }
        }
        return ans;
    }

    private int helper(int[] A, int[] B, int val) {
        int ansTop = 0, ansBottom = 0;

        for (int i = 0; i < A.length; i++) {
            if (A[i] != val && B[i] != val) {
                return -1;
            } else if (A[i] != val) {
                ansTop++;
            } else if (B[i] != val) {
                ansBottom++;
            }
        }

        return Math.min(ansTop, ansBottom);
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2