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

注意flip的意思,一次flip可以替换任意个数的牌的前、后数字,程序如下:

class Solution {
    public int flipgame(int[] fronts, int[] backs) {
        int[] frontMap = new int[2001];
        int[] backMap = new int[2001];
        int[] commonMap = new int[2001];
        for (int i = 0; i < fronts.length; ++ i){
            if (fronts[i] != backs[i]){
                frontMap[fronts[i]] = 1;
            }
            else {
                commonMap[backs[i]] ++;
            }
        }
        for (int i = 0; i < backs.length; ++ i){
            if (fronts[i] != backs[i]){
                backMap[backs[i]]  = 1;
            }
        }
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < backs.length; ++ i){
            if (frontMap[backs[i]] == 0 && commonMap[backs[i]] == 0){
                res = Math.min(res, backs[i]);
            }
            backMap[backs[i]] --;
            frontMap[backs[i]] ++;
            backMap[fronts[i]] ++;
            frontMap[fronts[i]] --;
            if (frontMap[fronts[i]] == 0 && commonMap[fronts[i]] == 0){
                res = Math.min(res, fronts[i]);
            }
            frontMap[fronts[i]] ++;
            backMap[fronts[i]] --;
            frontMap[backs[i]] --;
            backMap[backs[i]] ++;
        }
        return res == Integer.MAX_VALUE ? 0:res;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值