[Swift]LeetCode822. 翻转卡片游戏 | Card Flipping Game
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10567261.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
On a table are N
cards, with a positive integer printed on the front and back of each card (possibly different).
We flip any number of cards, and after we choose one card.
If the number X
on the back of the chosen card is not on the front of any card, then this number X is good.
What is the smallest number that is good? If no number is good, output 0
.
Here, fronts[i]
and backs[i]
represent the number on the front and back of card i
.
A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
Example:
2
[1,3,4,4,7]
[1,2,4,1,3]
2
Note:
1 <= fronts.length == backs.length <= 1000
.1 <= fronts[i] <= 2000
.1 <= backs[i] <= 2000
.
在桌子上有 N
张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。
我们可以先翻转任意张卡片,然后选择其中一张卡片。
如果选中的那张卡片背面的数字 X
与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。
哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0。
其中, fronts[i]
和 backs[i]
分别代表第 i
张卡片的正面和背面的数字。
如果我们通过翻转卡片来交换正面与背面上的数,那么当初在正面的数就变成背面的数,背面的数就变成正面的数。
示例:
2
[1,3,4,4,7]
[1,2,4,1,3]。
提示:
1 <= fronts.length == backs.length <= 1000
1 <= fronts[i] <= 2000
1 <= backs[i] <= 2000
1 class Solution { 2 func flipgame(_ fronts: [Int], _ backs: [Int]) -> Int { 3 var res:Int = Int.max 4 var n:Int = fronts.count 5 var same:Set<Int> = Set<Int>() 6 for i in 0..<n 7 { 8 if fronts[i] == backs[i] 9 { 10 same.insert(fronts[i]) 11 } 12 } 13 for front in fronts 14 { 15 if !same.contains(front) 16 { 17 res = min(res, front) 18 } 19 } 20 for back in backs 21 { 22 if !same.contains(back) 23 { 24 res = min(res, back) 25 } 26 } 27 return res == Int.max ? 0 : res 28 } 29 }
92ms
1 class Solution { 2 func flipgame(_ fronts: [Int], _ backs: [Int]) -> Int { 3 var sameSets = Set<Int>() 4 for i in fronts.indices { 5 if fronts[i] == backs[i] { 6 sameSets.insert(fronts[i]) 7 } 8 } 9 10 var ans = Int.max 11 let arr = fronts+backs 12 for x in arr { 13 if !sameSets.contains(x) { 14 ans = min(ans, x) 15 } 16 } 17 return ans == Int.max ? 0 : ans 18 } 19 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了