Leetcode 136 Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Constraints:
1 <= nums.length <= 3 * 10^4
-3 * 10^4 <= nums[i] <= 3 * 10^4
Each element in the array appears twice except for one element which appears only once.
Analysis:
If there is no space limitation, this question can be solved by counting easily.
But counting requires additional space.
Here we can use xor (^) operation based on some interesting observations:
A^A = 0, here A is any number
A^0 = A, here A is any number
Since all the number appears twice except one, then all the number appear even numbers will be cancelled out, and only the number appears one time is left, which is what we want.
See the code below:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(auto &a : nums) {
res ^= a;
}
return res;
}
};
Comments
Post a Comment