您的位置:首页 > 其它

Leetcode 136 只出现一次的数字

2019-02-20 13:57 513 查看
版权声明:版权归博主所有,转载请注明 https://blog.csdn.net/qq_17808707/article/details/87793301

题目描述

定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:
输入: [2,2,1]
输出: 1

示例 2:
输入: [4,1,2,1,2]
输出: 4

解题思路

一个不符合题目要求的解法。采用collections库中的Counter对数组进行计数,找到计数为1的键并返回。

代码

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
from collections import Counter
c=Counter(nums)
for key in c.keys():
if c[key]==1:
return key

结果

反思

采用异或运算可以很简单的解决此问题。异或:当两个位相同时,结果为0,当两个数不同时,结果为1。异或同一个数两次,原数不变。
代码如下:

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res=0
for n in nums:
res ^= n
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: