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.

 

题目理解:

给定一组“卡片”,卡片的正反面都有数字,并且可以任意的翻转使得某一面朝上。定义“好数”:当一个卡片朝下一面的数字在所有朝上的数字中没有出现,那么称这个数为“好数”。求出最小的“好数”

解题思路:

如果某一个卡片的正反两面的数字相同,那么它一定不是一个“好数”,因为一定有一个和它一样的数字朝上。其他的数字都可以是“好数”,在剩余的数字中找到一个最小的就行了

class Solution {
    public int flipgame(int[] fronts, int[] backs) {
        int len = fronts.length;
        Set set = new HashSet<>();
        List list = new ArrayList<>();
        for(int i = 0; i < len; i++){
            if(fronts[i] == backs[i])
                set.add(fronts[i]);
        }
        int res = Integer.MAX_VALUE;
        for(int i = 0; i < len; i++){
            if(!set.contains(fronts[i]))
                res = Math.min(res, fronts[i]);
            if(!set.contains(backs[i]))
                res = Math.min(res, backs[i]);
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

 

你可能感兴趣的:(LeetCode)