[LeetCode]Card Flipping Game

题目描述:

LeetCode 822. Card Flipping Game

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. 1 <= fronts.length == backs.length <= 1000.
  2. 1 <= fronts[i] <= 2000.
  3. 1 <= backs[i] <= 2000.

题目大意:

在桌上有N张纸牌,其正反面各有一个正整数(可能不同)。

你可以翻转任意数量的纸牌,然后挑选一张。

如果这张纸牌背面的数字没有在任何一张纸牌的正面出现过,则该纸牌正面的数字是有效的。

求最小的有效值。

解题思路:

蛮力法(Brute Force)

从小到大遍历每一个可能的数字,逐一验证。

Python代码:

class Solution(object):
    def flipgame(self, fronts, backs):
        """
        :type fronts: List[int]
        :type backs: List[int]
        :rtype: int
        """
        numbers = set(fronts + backs)
        for n in sorted(numbers):
            if all(f != n or b != n for f, b in zip(fronts, backs)):
                return n
        return 0

 

本文链接:http://bookshadow.com/weblog/2018/04/22/leetcode-card-flipping-game/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论