★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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:
Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] Output:2
Explanation: If we flip the second card, the fronts are[1,3,4,4,7]
and the backs are[1,2,4,1,3]
. We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so2
is good.
Note:
1 <= fronts.length == backs.length <= 1000
.1 <= fronts[i] <= 2000
.1 <= backs[i] <= 2000
.
在桌子上有 N
张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。
我们可以先翻转任意张卡片,然后选择其中一张卡片。
如果选中的那张卡片背面的数字 X
与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。
哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0。
其中, fronts[i]
和 backs[i]
分别代表第 i
张卡片的正面和背面的数字。
如果我们通过翻转卡片来交换正面与背面上的数,那么当初在正面的数就变成背面的数,背面的数就变成正面的数。
示例:
输入:fronts = [1,2,4,4,7], backs = [1,3,4,1,3] 输出:2
解释:假设我们翻转第二张卡片,那么在正面的数变成了[1,3,4,4,7]
, 背面的数变成了[1,2,4,1,3]。
接着我们选择第二张卡片,因为现在该卡片的背面的数是 2,2 与任意卡片上正面的数都不同,所以 2 就是我们想要的数字。
提示:
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 }