Python 中的单个数字
pythonserver side programmingprogramming更新于 2025/10/27 0:44:17
假设我们有一个数组 A。在这个数组中有很多出现两次的数字。每次只能找到一个元素。我们必须从该数组中找到该元素。假设 A = [1, 1, 5, 3, 2, 5, 2],则输出为 3。由于每个数字都出现了两次,我们可以执行 XOR 来抵消该元素。因为我们知道 y XOR y = 0
为了解决这个问题,我们将遵循以下步骤。
- 取一个变量 res = 0
- 对于数组 A 中的每个元素 e,执行 res = res XOR e
- 返回 res
示例
让我们看下面的实现,以便更好地理解 −
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ans = nums[0] for i in range(1,len(nums)): ans ^=nums[i] return ans ob1 = Solution() print(ob1.singleNumber([1,1,5,3,2,5,2]))
输入
nums = [1,1,5,3,2,5,2]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

