540. Single Element in a Sorted Array
- Single Element in a Sorted Array python solution
题目描述
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
解析
题目的意思非常的简单,只要寻找出数组中唯一一个只出现一次的数字。
使用异或进行寻找,因为A^A=0。
所以对整个数组进行异或操作,最后剩下的就是只出现过一次的元素。
from functools import reduce
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
return reduce(lambda x, y: x^y, nums)
Reference
https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/474048/Python3-O(N)-O(1)-bitwise-XOR