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
本文介绍了一种在已排序数组中寻找唯一出现一次元素的高效算法。通过使用异或运算,我们可以在O(N)的时间复杂度和O(1)的空间复杂度下解决这个问题。文章提供了一个Python实现的例子。
646

被折叠的 条评论
为什么被折叠?



