Skip to content

Latest commit

 

History

History
34 lines (23 loc) · 965 Bytes

0136. Single Number.md

File metadata and controls

34 lines (23 loc) · 965 Bytes

题目

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

我的思路

这道题要求找出一组数中只出现1次的数字,而其他数字都出现2次。首先我想到遍历数组,创建字典,这种方式可以在线性时间复杂度内求解,但题目要求不使用额外的空间,所以重新查看其他方法。发现python位运算中的异或可以解决,相同的数异或后为0 ,最后就剩下那个只出现一次的数。

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        for i in range(1,len(nums)):
            nums[0] = nums[0] ^ nums[i]
        return nums[0]