136. Single Number
Approach 4: Bit Manipulation
Concept
- If we take XOR of zero and some bit, it will return that bit
- If we take XOR of two same bits, it will return 0
So we can XOR all bits together to find the unique number.
Implementation
class Solution {
public int singleNumber(int[] nums) {
int a = 0;
for (int i : nums) {
a ^= i;
}
return a;
}
}
Java
class Solution {
public int singleNumber(int[] nums) {
int a = 0;
for (int i : nums) {
a ^= i;
}
return a;
}
}
Python
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
Complexity Analysis
- Time complexity : . We only iterate through
nums
, so the time complexity is the number of elements innums
. - Space complexity : .