当前位置: 首页 > news >正文

【Leetcode 每日一题 - 补卡】1007. 行相等的最少多米诺旋转

问题背景

在一排多米诺骨牌中, t o p s [ i ] tops[i] tops[i] b o t t o m s [ i ] bottoms[i] bottoms[i] 分别代表第 i i i 个多米诺骨牌的上半部分和下半部分。(一个多米诺是两个从 1 1 1 6 6 6 的数字同列平铺形成的 —— 该平铺的每一半上都有一个数字。)
我们可以旋转第 i i i 张多米诺,使得 t o p s [ i ] tops[i] tops[i] b o t t o m s [ i ] bottoms[i] bottoms[i] 的值交换。
返回能使 t o p s tops tops 中所有值或者 b o t t o m s bottoms bottoms 中所有值都相同的最小旋转次数。
如果无法做到,返回 − 1 -1 1

数据约束

  • 2 ≤ t o p s . l e n g t h ≤ 2 × 1 0 4 2 \le tops.length \le 2 \times 10 ^ 4 2tops.length2×104
  • b o t t o m s . l e n g t h = t o p s . l e n g t h bottoms.length = tops.length bottoms.length=tops.length
  • 1 ≤ t o p s [ i ] , b o t t o m s [ i ] ≤ 6 1 \le tops[i], bottoms[i] \le 6 1tops[i],bottoms[i]6

解题过程

结果要求所有元素都相同,那这意味着如果最后能实现,那么取初始状态的任意一个元素,它或它的翻转状态一定被包含在结果中。
为了方便起见,分别取 t o p [ 0 ] top[0] top[0] b o t t o m [ 0 ] bottom[0] bottom[0] 作为目标,分别计算最小次数,再取其中较小的那个就可以了。

具体实现

class Solution {public int minDominoRotations(int[] tops, int[] bottoms) {int res = Math.min(minRot(tops, bottoms, tops[0]), minRot(tops, bottoms, bottoms[0]));return res == Integer.MAX_VALUE ? -1 : res;}private int minRot(int[] tops, int[] bottoms, int target) {int toTop = 0;int toBottom = 0;for (int i = 0; i < tops.length; i++) {int x = tops[i];int y = bottoms[i];if (x != target && y != target) {return Integer.MAX_VALUE;}if (x != target) {toTop++; } else if (y != target) {toBottom++;}}return Math.min(toTop, toBottom);}
}

相关文章:

  • 「Mac畅玩AIGC与多模态20」开发篇16 - 使用结构化输出字段控制后续流程示例
  • Three.js + React 实战系列 - 客户评价区细解教程 Clients 组件✨(回答式评价 + 评分星级)
  • ​亚马逊云服务器技术全景解析:从基础架构到行业赋能​
  • JVM——Java对象的内存布局
  • 价格识别策略思路
  • 数智管理学(六)
  • D. Pythagorean Triples 题解
  • Vuex使用指南:状态管理
  • JavaWeb:MySQL基础
  • shell(9)
  • ts学习(1)
  • Linux的时间同步
  • 湖北理元理律师事务所:规模化债事服务的探索与实践
  • 偷钱包行为检测数据集VOC+YOLO格式922张1类别有增强
  • 嵌入式模数转换原理与程序设计
  • 3小时超快速入门Python
  • Java IO流分类与记忆方法
  • AfuseKt2.4.2 | 支持阿里云盘、Alist等平台视频播放,具备自动海报墙刮削功能的强大播放器
  • ctfshow——web入门361~368
  • ADK 第四篇 Runner 执行器
  • 言短意长|党政主官如何塑造流量城市?
  • 许昌市场监管部门对胖东来玉石开展日常检查:平均毛利率不超20%
  • 贵州省委省政府迅速组织开展黔西市游船倾覆事故救援工作
  • 两千万粉丝网红“大LOGO”带货茶叶被指虚假宣传,涉事茶企被立案调查
  • 给3亿老人爆改房子,是门好生意吗?
  • 陈燮阳从艺60周年:指挥棒不停,心跳就不会老去