leetcode1007-行相等的最少多米诺旋转

题目描述

  • 有两个等长的数组,索引相同的地方可以交换数字
  • 如果交换若干次可以使其中一个数组的值唯一,返回次数
  • 如果无法做到,返回 -1

示例

输入:
tops =    [2,1,2,4,2,2]
bottoms = [5,2,6,2,3,2]
输出:2
输入:
tops =    [3,5,1,2,3]
bottoms = [3,6,3,3,4]
输出:-1

题解

  • 思路
    1. (tops[i], bottoms[i]) 为一组,统计数字出现的次数,一组中的同一数字最多累加一次
    2. 如果上下数字不同,额外记录一下次数,用作之后的统计(如果该数字是目标,那么统计的次数就是可能的结果)
    3. 遍历第一步的统计结果,若能找到目标数字,就去第二步的统计结果中找更小的值;若没找到目标数字,则返回 -1
func minDominoRotations(tops []int, bottoms []int) int {
    nums, ts, bs := [7]int{}, [7]int{}, [7]int{}
    for i := 0; i < len(tops); i ++ {
        x, y := tops[i], bottoms[i]
        if x == y {
            nums[x] ++
        } else {
            nums[x] ++
            ts[x] ++
            nums[y] ++
            bs[y] ++
        }
    }

    for k, v := range nums {
        if v == len(tops) {
            return min(ts[k], bs[k])
        }
    }
    return -1
}
posted @ 2025-08-25 20:40  余越  阅读(9)  评论(0)    收藏  举报