Given a non-empty array of integers nums
every element appears twice except for one. Find that single/unique integer value.
Constraints:
Example 1:
nums = [2,2,1]
1
Example 2:
nums = [4,1,2,1,2]
4
Example 3:
nums = [1]
1
/**
* Find unique element in the array using HashSet.
* TC: O(n)
* SC: O(n)
*
* @param nums
* @return
*/
public static int findSingleNumberHashSet(int[] nums) {
final Set<Integer> numSet = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
int t = nums[i];
if (numSet.contains(t)) {
numSet.remove(t);
} else {
numSet.add(t);
}
}
if (numSet.size() == 1) {
return numSet.iterator().next();
} else {
return 0;
}
}
/**
* Find Unique number in an array using Bitwise XOR operator.
* TC: O(n)
* SC: O(1)
*
* @param nums
* @return
*/
public static int findSingleNumberBitwiseXor(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res ^ nums[i];
}
return res;
}