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:2Explanation: 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, so2is good.
Note:
1 <= fronts.length == backs.length <= 1000.1 <= fronts[i] <= 2000.1 <= backs[i] <= 2000.
這道題剛開始的時候博主一直沒看懂題意,不知所雲,后來逛了論壇才總算弄懂了題意,說是給了一些正反都有正數的卡片,可以翻面,讓我們找到一個最小的數字,在卡的背面,且要求其他卡正面上均沒有這個數字。簡而言之,就是要在backs數組找一個最小數字,使其不在fronts數組中。我們想,既然不能在fronts數組中,說明卡片背面的數字肯定跟其正面的數字不相同,否則翻來翻去都是相同的數字,肯定會在fronts數組中。那么我們可以先把正反數字相同的卡片都找出來,將數字放入一個HashSet,也方便我們后面的快速查找。現在其實我們只需要在其他的數字中找到一個最小值即可,因為正反數字不同,就算fronts中其他卡片的正面還有這個最小值,我們可以將那張卡片翻面,使得相同的數字到backs數組,總能使得fronts數組不包含有這個最小值,就像題目中給的例子一樣,數字2在第二張卡的背面,就算其他卡面也有數字2,只要其不是正反都是2,我們都可以將2翻到背面去,參見代碼如下:
class Solution { public: int flipgame(vector<int>& fronts, vector<int>& backs) { int res = INT_MAX, n = fronts.size(); unordered_set<int> same; for (int i = 0; i < n; ++i) { if (fronts[i] == backs[i]) same.insert(fronts[i]); } for (int front : fronts) { if (!same.count(front)) res = min(res, front); } for (int back : backs) { if (!same.count(back)) res = min(res, back); } return (res == INT_MAX) ? 0 : res; } };
參考資料:
https://leetcode.com/problems/card-flipping-game/
