[LeetCode] Card Flipping Game 翻卡片遊戲

 

On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).html

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.post

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 iurl

A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.spa

Example:code

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:htm

  1. 1 <= fronts.length == backs.length <= 1000.
  2. 1 <= fronts[i] <= 2000.
  3. 1 <= backs[i] <= 2000.
 

這道題剛開始的時候博主一直沒看懂題意,不知所云,後來逛了論壇才總算弄懂了題意,說是給了一些正反都有正數的卡片,能夠翻面,讓咱們找到一個最小的數字,在卡的背面,且要求其餘卡正面上均沒有這個數字。簡而言之,就是要在backs數組找一個最小數字,使其不在fronts數組中。咱們想,既然不能在fronts數組中,說明卡片背面的數字確定跟其正面的數字不相同,不然翻來翻去都是相同的數字,確定會在fronts數組中。那麼咱們能夠先把正反數字相同的卡片都找出來,將數字放入一個HashSet,也方便咱們後面的快速查找。如今其實咱們只須要在其餘的數字中找到一個最小值便可,由於正反數字不一樣,就算fronts中其餘卡片的正面還有這個最小值,咱們能夠將那張卡片翻面,使得相同的數字到backs數組,總能使得fronts數組不包含有這個最小值,就像題目中給的例子同樣,數字2在第二張卡的背面,就算其餘卡面也有數字2,只要其不是正反都是2,咱們均可以將2翻到背面去,參見代碼以下:blog

 

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;
    }
};

 

參考資料:ip

https://leetcode.com/problems/card-flipping-game/

https://leetcode.com/problems/card-flipping-game/discuss/125791/C%2B%2BJavaPython-Easy-and-Concise-with-Explanation

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索