1.Description
There is an integer array. In this array, only one element appears once and other elements appears twice. The task is to find the element which appears once using an algorithm whose time complexity is O(n) and space complexity is O(1).
2.Algorithms I used
XOR operations
3.Analysis
At first, I use QuickSort to solve this problem. By using QuickSort, the array becomes ordered. For an ascending array, we can find the element which appears once by iterating the array, While iterating, we compare one element and its former element. If they are not equal, the current element is the answer. I have completed it below.
class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
if(nums.size() == 1) return nums[0];
if(nums[0] != nums[1]) return nums[0];
if(nums[nums.size()-1] != nums[nums.size()-2]) return nums[nums.size()-1];
for(int i = 0;i < nums.size();i+=2){
if(nums[i] != nums[i+1])
return {nums[i]};
}
return 0;
}
};
However, this solution’s time complexity is O(nlogn). It doesn’t meet the requirement.
I didn’t come up with a better answer.
After reading other’s solution, I know that this problem should be solved by XOR operations. For this problem, we have to know 3 rules about XOR.
First, any number XOR 0 remains 0.
Second, the XOR result of two same numbers is 0 and the XOR result of two different numbers is 1.
Third, XOR operation satisfys the commutative law and the associate law.
Hence, we can XOR all elements in the array. By using the commutative law, the final equation is 0XOR0XOR0XOR0…XORans. Every 0 in this equation is a XOR result of two same numbers. And ans is the element we want.
4.code
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0;i < nums.size();i++){
ans ^= nums[i];
}
return ans;
}
};
5.Complexity
TIme complexity: O(n).
Space complexity: O(1).