We need to find all numbers that appear exactly twice in the array and return their XOR. We can use a hash map (or array) to count occurrences, then XOR all numbers with count 2.
classSolution {
public:int duplicateNumbersXOR(vector<int>& nums) {
unordered_map<int, int> cnt;
for (int x : nums) cnt[x]++;
int ans =0;
for (auto& [k, v] : cnt) if (v ==2) ans ^= k;
return ans;
}
};
1
2
3
4
5
6
7
8
9
funcduplicateNumbersXOR(nums []int) int {
cnt:=map[int]int{}
for_, x:=rangenums { cnt[x]++ }
ans:=0fork, v:=rangecnt {
ifv==2 { ans ^= k }
}
returnans}
1
2
3
4
5
6
7
8
9
classSolution {
publicintduplicateNumbersXOR(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = 0;
for (var e : cnt.entrySet()) if (e.getValue() == 2) ans ^= e.getKey();
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funduplicateNumbersXOR(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1var ans = 0for ((k, v) in cnt) if (v ==2) ans = ans xor k
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defduplicateNumbersXOR(self, nums: list[int]) -> int:
from collections import Counter
cnt = Counter(nums)
ans =0for k, v in cnt.items():
if v ==2:
ans ^= k
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnduplicate_numbers_xor(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
letmut cnt = HashMap::new();
for&x in&nums { *cnt.entry(x).or_insert(0) +=1; }
letmut ans =0;
for (&k, &v) in&cnt {
if v ==2 { ans ^= k; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
classSolution {
duplicateNumbersXOR(nums: number[]):number {
constcnt: Record<number, number> = {};
for (constxofnums) cnt[x] = (cnt[x] ||0) +1;
letans=0;
for (constkincnt) if (cnt[k] ===2) ans^=+k;
returnans;
}
}