【LeetCode】【136. Single Number】(python版)

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 1:

Input: [2,2,1]
Output: 1

Example 2:

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

思路:

题目给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。要求线性时间复杂度。

1、适用于所有求次数的题目,一次遍历数组,key为数字,value为出现次数,存入hash表,再次遍历数组,找到hash表中value为1的key。两次遍历时间复杂度为 O(2n) O ( 2 n ) ,空间复杂度 O(n/2) O ( n / 2 )

2、考虑2∗(a+b+c)−(a+a+b+b+c)=c,因为使用set保存出现过的数字,因此复杂度同上

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return 2 * sum(set(nums)) - sum(nums)

3、利用异或运算性质
a0=a a ⊕ 0 = a
aa=0 a ⊕ a = 0
aba=(aa)b=0b=b a ⊕ b ⊕ a = ( a ⊕ a ) ⊕ b = 0 ⊕ b = b

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 fucntools 模块里,如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数:
        from functools import reduce

        # reduce() 函数会对参数序列中元素进行累积。函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
        return reduce(lambda x, y: x ^ y, nums)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值