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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_20141867/article/details/82314035

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 ( 2 n ) ,空间复杂度 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、利用异或运算性质
a 0 = a
a a = 0
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)

猜你喜欢

转载自blog.csdn.net/qq_20141867/article/details/82314035
今日推荐