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等
实现:
1 class Solution: 2 # @param {integer[]} nums 3 # @return {integer} 4 def singleNumber(self, nums): 5 result = nums[0] 6 for i in range(1, len(nums)): 7 result ^= nums[i] 8 return result 9