zoukankan      html  css  js  c++  java
  • 04 LeetCode --- 反转整数

    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

    说明:

    你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

    示例 1:

    输入: [2,2,1]
    输出: 1

    示例 2:

    输入: [4,1,2,1,2]
    输出: 4

    思路

    很容易想到的2个方法是:

    1. 用list.count()方法统计只出现一次的个数,很不幸的是,这个超时
    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            X = [i for i in nums if nums.count(i) == 1]
            return x[0]

      2.  用collections.Counter(),会返回一个字典,key为元素,value为元素出现的次数,只要找到value小于2的就好了,虽然没有超时,但是效率也不够让人满意,才超越了10%左右

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            x = collections.Counter(nums)
            for key,value in x.items():
                if value < 2:
                    return key

    改进的版本

    提交后看了最快的代码,思路是运用按位异或运算符,当两对应的二进位相异结果为1,真值表如下:

    abc
    0 0 0
    0 1 1
    1 0 1
    1 1 0

    可以看出如果有两个元素是相等的,按位与的结果会是0,而0与任何数都等于这个数本身

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            result = 0
            for num in nums:
                result = result ^ num     
            return result
  • 相关阅读:
    haskell的分数运算
    我的自画像
    秋 天 19:4320:05
    不要逼孩子考100分
    看图写话
    转载:挺住,意味着一切
    Wpf UI框架 MaterialDesign 的使用记录
    通过蓝牙的RSSI计算两端之间的距离(一维定位)
    java tcp socket readline 阻塞问题处理
    Android Back返回键 退出
  • 原文地址:https://www.cnblogs.com/yanyufeng/p/9883460.html
Copyright © 2011-2022 走看看