LC.P822[翻转卡片游戏]

方法一:哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int flipgame(int[] fronts, int[] backs) {
Set<Integer> set = new HashSet<>();
int n = fronts.length, ans = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i) {
if (fronts[i] == backs[i]) set.add(fronts[i]);
}
for (int x : fronts) {
if (!set.contains(x)) ans = Math.min(ans, x);
}
for (int x : backs) {
if (!set.contains(x)) ans = Math.min(ans, x);
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$