You are given an array nums
, where each number in the array appears either once or twice.
Return the bitwise XOR
of all the numbers that appear twice in the array, or 0 if no number appears twice.
LeetCode Problem - 3158
import java.util.HashMap;
import java.util.Map;
class Solution {
public int duplicateNumbersXOR(int[] nums) {
// Create a HashMap to store the frequency of each number in the array
Map<Integer, Integer> map = new HashMap<>();
// Iterate over each number in the array
for (int num : nums) {
// Increment the count of the number in the map
map.put(num, map.getOrDefault(num, 0) + 1);
}
// Initialize a variable to hold the XOR of duplicate numbers
int xor = 0;
// Iterate over the keys in the map (unique numbers in the array)
for (int num : map.keySet()) {
// Get the frequency of the current number
int value = map.get(num);
// If the number appears exactly twice, XOR it with the current xor value
if (value == 2) xor ^= num;
}
// Return the final XOR result
return xor;
}
}