zoukankan      html  css  js  c++  java
  • leecode第二天-使用异或找出数组中的非重复元素

    leecode题目描述如下:
    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

    思路:
    最开始想到的是使用排序,排序之后就很容易找到非重复元素了。
    后面看到网上有更巧妙的解决办法,即使用异或来找出非重复元素,因为重复的元素经异或之后就互相抵消为0了,最后数组各个元素经过异或计算之后的结果就是那个唯一的非重复元素。

    代码:

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            num = 0
            for i in nums:
                num = num ^ i
            return num
    
    def stringToIntegerList(input):
        return json.loads(input)
    
    def intToString(input):
        if input is None:
            input = 0
        return str(input)
    
    def main():
        import sys
        def readlines():
            for line in sys.stdin:
                yield line.strip('
    ')
        lines = readlines()
        while True:
            try:
                line = lines.next()
                nums = stringToIntegerList(line)
                
                ret = Solution().singleNumber(nums)
    
                out = intToString(ret)
                print out
            except StopIteration:
                break
    
    if __name__ == '__main__':
        main()
    
    
  • 相关阅读:
    VMware虚拟机安装
    代码搜索的终极武器Ag
    模糊搜索神器fzf
    Python:json、xml、字典各种转换
    03-azkaban安装部署
    linux下环境变量PATH设置错误的补救
    01-编译azkaban
    VMware安装CentOS7
    PS(二)
    等待公交车的时间
  • 原文地址:https://www.cnblogs.com/worthy/p/9534556.html
Copyright © 2011-2022 走看看