【LeetCode】822. Card Flipping Game 解題報告(Python)
題目描述:
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, so 2 is good.
Note:
- 1 <= fronts.length == backs.length <= 1000.
- 1 <= fronts[i] <= 2000.
- 1 <= backs[i] <= 2000.
題目大意
有一些正反面都有數字的牌,我們可以做很多次翻轉操作,每次翻轉時如果這個牌背面的數字沒有在這群牌的正面出現過,那麼就可以把這個牌翻轉過來。求翻轉哪個牌可以之後,可以使得所有牌正面中的最小值最小。
解題方法
這個題的英文描述不清,我儘量翻譯的清楚了。
所以,如果一個牌正反面相等,那麼翻轉不翻轉沒什麼意義。否則可以翻轉,求翻哪些之後會得到最小,就是如果不翻轉的最小值和翻轉了之後的最小值的最小值。使用set儲存一下正反面相等的數字,這些是一定不能在正面出現的,然後找出不在這個set裡面的正反面的最小值即可。
怎麼理解?首先正反面相同的翻轉沒有意義,然後找在正反面的最小值把它翻轉到正面來。那麼有人會想,如果翻轉這個牌和其他的正面的牌有衝突怎麼辦?其實,如果和set裡面的牌有衝突沒有意義,如果和不在set裡面的正面的牌有衝突就把這個衝突的牌也翻轉即可。所以,不用考慮這麼多。。
時間複雜度是O(N),空間複雜度最壞是O(N).
程式碼如下:
class Solution:
def flipgame(self, fronts, backs):
"""
:type fronts: List[int]
:type backs: List[int]
:rtype: int
"""
s = set()
res = float('inf')
for f, b in zip(fronts, backs):
if f == b:
s.add(f)
for f in fronts:
if f not in s:
res = min(res, f)
for b in backs:
if b not in s:
res = min(res, b)
return 0 if res == float('inf') else res
參考資料:
日期
2018 年 9 月 27 日 ———— 今天起得格外早