【leetcode】(python)136. Single Number单数


136. Single Number Easy

Description

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

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

题意

求一非空数组中只出现一次的数

解题思路

最开始是想用字典dict比较方便,而题目要求时间复杂度为O(n),且不借助辅助空间。参考异或的解法,也很方便。

笔记:

^ :按位异或运算符:当两对应的二进位相异时,结果为1。
示例:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0c = a ^ b; # 49 = 0011 0001
print(“3 - c 的值为:”, c)

c 的值为: 49

dict code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        if nums == []:
            return 0
        dic = collections.defaultdict(int)
        for i in nums:
            dic[i] += 1
        print(dic)
        for key,value in dic.items():
            if value % 2 != 0:
                return key

异或 code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        if nums == []:
            return 0
        res = 0
        for num in nums:
            res = res ^ num
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值