美文网首页
[刷题]Leetcode-136:Single Number(只

[刷题]Leetcode-136:Single Number(只

作者: firewt | 来源:发表于2018-12-23 20:13 被阅读4次

    原文链接:[刷题]Leetcode-136:Single Number(只出现一次的数字) - 高歌的博客

    题目详情

    题目描述:
    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
    说明:
    你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
    示例 1:
    输入: [2,2,1]
    输出: 1
    示例 2:
    输入: [4,1,2,1,2]
    输出: 4
    
    class Solution:
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    

    解题思路

    首先想到了用暴力搜索的方式,新建一个s list,对nums中的元素逐一迭代,判断元素是否在s中,如果s存在迭代的元素,则否定该元素,直到找到唯一的数字,这个思路最容易想到,代码也很容易写出就不展示了,但是最后结果肯定是超时,因为题目的考察重点不在于此。同样用python自带的list.count(i)的方式也会超时,因为本质上还是在暴力搜索。

    因为只有一个元素是出现一次的,很容易想到了异或运算,二进制位相同为0相异为1,这样可以用一个变量做筛选,只需要len(nums)次异或运算就能找到结果,尝试解题方案如下:

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

    通过,耗时在100ms之内,翻看其他人的解体方案,一个很巧妙的方案:

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

    因为只有一个元素出现一次,直接set去重求2倍和,然后和nums的和相减直接get目标,nice!

    相关文章

      网友评论

          本文标题:[刷题]Leetcode-136:Single Number(只

          本文链接:https://www.haomeiwen.com/subject/bpjffqtx.html