You are given a non-empty array of integers nums. Every integer appears twice except for one.
Return the integer that appears only once.
You must implement a solution with runtime complexity and use only extra space.
Example 1:
Input: nums = [3,2,3]
Output: 2Example 2:
Input: nums = [7,6,6,7,8]
Output: 8Constraints:
1 <= nums.length <= 10000-10000 <= nums[i] <= 10000
You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.
A brute force approach would iterate through the array, checking each element using a nested loop. If a duplicate is found, we continue to the next element; otherwise, the current element is the required number. This results in an O(n^2) solution. Can you think of a better way? Maybe a data structure can help detect duplicates efficiently.
We use a hash set, iterating through the array and adding elements that are not in the set while removing those that are already present. After the iteration, the required number remains in the hash set. This results in an O(n) space solution. Can you further optimize it? Maybe a bitwise operator could be useful here.
Think about the bitwise XOR ("^"). What is the result when two identical numbers are XORed?
When two identical numbers are XORed, they cancel out, resulting in zero. Since every number appears twice except for one, the XOR of the entire array gives the number that appears only once.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in range(len(nums)):
flag = True
for j in range(len(nums)):
if i != j and nums[i] == nums[j]:
flag = False
break
if flag:
return nums[i]class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen = set()
for num in nums:
if num in seen:
seen.remove(num)
else:
seen.add(num)
return list(seen)[0]class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
i = 0
while i < len(nums) - 1:
if nums[i] == nums[i + 1]:
i += 2
else:
return nums[i]
return nums[i]class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for num in nums:
res = num ^ res
return res