2023-08-02 LeetCode每日一题(翻转卡片游戏)

2023-08-02每日一题

一、题目编号

822. 翻转卡片游戏

二、题目链接

点击跳转到题目位置

三、题目描述

在桌子上有 N 张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。

我们可以先翻转任意张卡片,然后选择其中一张卡片。

如果选中的那张卡片背面的数字 X 与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。

哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0。

其中, fronts[i] 和 backs[i] 分别代表第 i 张卡片的正面和背面的数字。

如果我们通过翻转卡片来交换正面与背面上的数,那么当初在正面的数就变成背面的数,背面的数就变成正面的数。

示例1:
2023-08-02 LeetCode每日一题(翻转卡片游戏)_第1张图片
示例2:
2023-08-02 LeetCode每日一题(翻转卡片游戏)_第2张图片

提示:

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

四、解题代码

class Solution {
public:
    int flipgame(vector<int>& fronts, vector<int>& backs) {
        int res = 3000, 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 &x : fronts) {
            if (x < res && same.count(x) == 0) {
                res = x;
            }
        }
        for (int &x : backs) {
            if (x < res && same.count(x) == 0) {
                res = x;
            }
        }
        return res % 3000;
    }
};

五、解题思路

(1) 使用哈希表解决问题。

你可能感兴趣的:(LeetCode每日一题,leetcode,算法,数据结构)