Several approaches can be used to solve this problem. Here, I will introduce two commonly used methods: one utilizing a hash table and the other employing the XOR operation.
Method One: Using a Hash Table
Using a hash table to track the frequency of each element in the array, then iterating through the hash table to identify the element that appears only once.
Steps:
- Initialize an empty hash table.
- Iterate through the array. For each element, if it is not present in the hash table, add it with a count of 1; otherwise, increment its count.
- Iterate through the hash table again to find the element with a count of 1.
Code Example (Python):
pythondef singleNumber(nums): count_map = {} for num in nums: if num in count_map: count_map[num] += 1 else: count_map[num] = 1 for num, count in count_map.items(): if count == 1: return num
Method Two: Using the XOR Operation
The XOR operation has a notable property: XORing any number with 0 yields the number itself, and XORing any number with itself yields 0. Utilizing this property, we can efficiently identify the number that appears only once.
Steps:
- Initialize a variable
resultto 0. - Iterate through the array, XORing each element with
result. - Since all numbers except one appear exactly twice, they will cancel each other out.
- The final value of
resultwill be the number that appears only once.
Code Example (Python):
pythondef singleNumber(nums): result = 0 for num in nums: result ^= num return result
Summary
In terms of time and space efficiency, the XOR approach is more efficient as it has a time complexity of O(n) and a space complexity of O(1). Conversely, the hash table method, while also having a time complexity of O(n), has a space complexity of O(n) due to the additional space required to store the elements and their counts.