Leetcode136-Single Number(Python3)

136. Single Number

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?

My Solution

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

Reference (转)

def singleNumber1(self, nums):
    dic = {}
    for num in nums:
        dic[num] = dic.get(num, 0)+1
    for key, val in dic.items():
        if val == 1:
            return key
def singleNumber2(self, nums):
    return 2*sum(set(nums))-sum(nums)
def singleNumber3(self, nums):
    return reduce(lambda x, y: x ^ y, nums)
def singleNumber4(self, nums):
    return reduce(operator.xor, nums)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 西江月。伊心痛 文/Chile. 深夜无星无月,窗儿勾引凉风。 吹来些点点残花,皆入梦谁晓痛。 不愿此生孤独,奈何...
    智Chile阅读 260评论 0 1
  • 文芾 我走进一间废弃的泥房子 从门洞、窗子、头顶上塌陷的屋顶 向外看—— 我像是站在记忆的中心 一些消失的事物 像...
    徐文显阅读 366评论 2 2
  • 我是一个将双手束之高阁的土人 我用尖细的眼睛审视着这片土地 眼珠转啊转啊 看到了农人亮晶晶的汗水 撒在了松软的土地...
    simbfry阅读 337评论 0 0