Skip to main content

540. Single Element in a Sorted Array

https://leetcode.com/problems/single-element-in-a-sorted-array

Python

Reduce

from functools import reduce


class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return reduce(lambda a, b: a^b, nums)

Set

  • Did not use the advantage of sorted condition
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
buffer = set()

for num in nums:
if num not in buffer:
buffer.add(num)
else:
buffer.remove(num)

return buffer.pop(