★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-yuljfmsg-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
On a table are N
cards, with a positive integer printed on the front and back of each card (possibly different).git
We flip any number of cards, and after we choose one card. github
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
.this
Here, fronts[i]
and backs[i]
represent the number on the front and back of card i
. spa
A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.code
Example:htm
Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] Output: Explanation: If we flip the second card, the fronts are and the backs are . We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so is good.2[1,3,4,4,7][1,2,4,1,3]2
Note:blog
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,2 与任意卡片上正面的数都不一样,因此 2 就是咱们想要的数字。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 }