SingleNumber python实现

时间:2025-01-22 23:05:32

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题意:一个整数数组中,除了一个数以外的其他数字都出现了两次,求这个只出现了一次的数。

要求:算法必须线性的时间复杂度,并且不需要额外的空间。

思路:主要利用异或的性质。交换性(a^b)^c=a^(b^c),以及a^0=a等

实现:

  

 class Solution:
# @param {integer[]} nums
# @return {integer}
def singleNumber(self, nums):
result = nums[0]
for i in range(1, len(nums)):
result ^= nums[i]
return result