力扣1007题解

记录

2025.5.3

题目:

力扣1007题解_第1张图片

思路:

若想一排相等则一排数字都等于第一个骨牌的数(tops或bottoms),遍历骨牌并判断所需的旋转次数(先tops再bottoms,最后判断谁小)。

解题步骤:

1.确定候选值:候选值必须是第一个骨牌的顶部或底部数字,因为如果存在解,它必须出现在第一个骨牌的至少一面上。
2.检查每个候选值的可行性:对于每个候选值,遍历所有骨牌,确保每个骨牌的顶部或底部至少有一个是候选值。若不可行,直接排除该候选值。
3.计算最小翻转次数:对于可行的候选值,分别统计将所有顶部或底部统一为该候选值所需的翻转次数,取较小值。
4.综合结果:比较两个候选值的结果,返回最小的可行解。若均不可行,返回 -1。

代码:

class Solution {
    public int minDominoRotations(int[] tops, int[] bottoms) {
        int a0 = tops[0];
        int a1= bottoms[0];       
        int result1 = wangh(a0, tops, bottoms);
        int result2 = wangh(a1, tops, bottoms);
        
        if (result1 == -1 && result2 == -1) {
            return -1;
        } else if (result1 == -1) {
            return result2;
        } else if (result2 == -1) {
            return result1;
        } else {
            return Math.min(result1, result2);
        }
    }

    private int wangh(int a, int[] tops, int[] bottoms) {
        int t0 = 0;
        int b0 = 0;  
        for(int x = 0 ;x < tops.length;x++){
           if(tops[x] != a && bottoms[x] != a){
               return -1;
           }
           if(tops[x] != a){
              t0++;
           }
           if(bottoms[x] != a){
            b0++;
           }
        }
        return Math.min(t0,b0);
    }
}

复杂度:

O(N)
O(1)

你可能感兴趣的:(leetcode,java,算法)