Leetcode-Algorithms Single Number

来源:互联网 发布:网络批发城 编辑:程序博客网 时间:2024/06/10 22:01

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?

给出一个integer的array,找出里面只出现过一次的数。

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        for p in range(1,len(nums)):            nums[0] ^= nums[p]        return nums[0]

XOR: 1^1 = 0, 0^3 = 3. 当len(nums)大于1时用XOR找single number。

0 0
原创粉丝点击