[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 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索