Python3 appear only once digital
Original title https://leetcode-cn.com/problems/single-number/
topic:
Given a non-empty array of integers, in addition to an element appears only once, the rest of each element appears twice. To find out that only appears once in the elements.
Description:
Your algorithm should have linear time complexity. You can not use the extra space to achieve it?
Example 1:
输入: [2,2,1]
输出: 1
Example 2:
输入: [4,1,2,1,2]
输出: 4
Problem solving:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in range(1, len(nums)):
nums[i] ^= nums[i-1] #使用异或运算即可,且不需要额外空间,不用reduce是因为那会使用额外的存储空间
return nums[-1]