跳到主要内容

822.翻转卡片游戏

链接:822.翻转卡片游戏
难度:Medium
标签:数组、哈希表
简介:哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0。

题解 1 - cpp

  • 编辑时间:2023-08-02
  • 执行用时:40ms
  • 内存消耗:24.54MB
  • 编程语言:cpp
  • 解法介绍:哈希存储。
class Solution {
public:
int flipgame(vector<int>& fronts, vector<int>& backs) {
int n = fronts.size(), res = INT_MAX;
unordered_map<int, vector<int>> mf, mb;
for (int i = 0; i < n; i++) {
mf[fronts[i]].push_back(i);
mb[backs[i]].push_back(i);
}
auto check = [&](unordered_map<int, vector<int>> &m, vector<int> &l, int val) -> bool {
for (auto &idx : m[val]) {
if (l[idx] == val) return false;
}
return true;
};
for (int i = 0; i < n; i++) {
if (!mf.count(fronts[i]) && !mb.count(fronts[i]) || check(mf, backs, fronts[i]) || check(mb, fronts, fronts[i])) {
res = min(res, fronts[i]);
}
if (!mf.count(backs[i]) && !mb.count(backs[i]) || check(mf, backs, backs[i]) || check(mb, fronts, backs[i])) {
res = min(res, backs[i]);
}
}
return res == INT_MAX ? 0 : res;
}
};

题解 2 - cpp

  • 编辑时间:2023-08-02
  • 执行用时:20ms
  • 内存消耗:18.66MB
  • 编程语言:cpp
  • 解法介绍:哈希存储。
class Solution {
public:
int flipgame(vector<int>& fronts, vector<int>& backs) {
int n = fronts.size(), res = 3000;
unordered_set<int> s;
for (int i = 0; i < n; i++) {
if (fronts[i] == backs[i]) s.insert(fronts[i]);
}
for (int i = 0; i < n; i++) {
if (!s.count(fronts[i])) res = min(res, fronts[i]);
if (!s.count(backs[i])) res = min(res, backs[i]);
}
return res % 3000;
}
};

题解 3 - python

  • 编辑时间:2023-08-02
  • 执行用时:52ms
  • 内存消耗:15.72MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
n = len(fronts)
res = 3000
s = set()
for i in range(n):
if fronts[i] == backs[i]:
s.add(fronts[i])
for i in range(n):
if not fronts[i] in s:
res = min(res, fronts[i])
if not backs[i] in s:
res = min(res, backs[i])
return res % 3000

题解 4 - rust

  • 编辑时间:2023-08-02
  • 执行用时:4ms
  • 内存消耗:1.96MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn flipgame(fronts: Vec<i32>, backs: Vec<i32>) -> i32 {
let n = fronts.len();
let mut s = std::collections::HashSet::<i32>::new();
let mut res = 3000;
for i in 0..n {
if fronts[i] == backs[i] {
s.insert(fronts[i]);
}
}
for i in 0..n {
if !s.contains(&fronts[i]) {
res = res.min(fronts[i]);
}
if !s.contains(&backs[i]) {
res = res.min(backs[i]);
}
}
res % 3000
}
}