您的位置:首页 > 编程语言 > Python开发

LeetCode136.python实现: 只出现一次的数字☆

2019-03-11 10:45 295 查看

目录

一、问题

二、解题思路

三、python具体实现

四、题外话

一、问题

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

[code]输入: [2,2,1]
输出: 1

示例 2:

[code]输入: [4,1,2,1,2]
输出: 4

二、解题思路

    分析:异或运算性质的考察:相同为0,不同为1. 异或同一个数两次,原数不变。(与0相异或,保留原值)

三、python具体实现

使用了2字节额外空间:

[code]class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in nums:
result = result^i   # 异或操作
return result

不使用额外空间实现:

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

 

四、题外话

     知道异或就会很简单,不知道就难住了。学到了! 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐