zoukankan      html  css  js  c++  java
  • 120-136. 只出现一次的数字

    问题描述:
          给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
    
    解释:其中前三种是我写的,后面两种是抄的
    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            set_nums = set(nums)
            for item in set_nums:
                if nums.count(item) == 1:
                    return item
            return -1
    
        def singleNumber1(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ret_dict = {}
            for item in nums:
                count = ret_dict.get(item, 0)
                if count == 1:
                    del ret_dict[item]
                    continue
                ret_dict[item] = count + 1
            return list(ret_dict.keys())[0]
    
        def singleNumber2(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            for i in nums:
                if nums.count(i) == 1:
                    return i
    
        def singleNumber3(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ret = 0
            for i in nums:
                ret = ret ^ i
            return ret
    
        def singleNumber4(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            return sum(set(nums))*2 - sum(nums)
    
    
    if __name__ == '__main__':
        s1 = Solution()
        nums = [4, 1, 2, 1, 2]
        print(s1.singleNumber4(nums))
    
    
  • 相关阅读:
    锦oa基础配置
    存储localStorage
    刷新token
    input框输入数量自动计算价格
    创建项目,登录校验
    config
    xiaota-main
    数据库的多表查询
    pygame应用---射击外星人游戏
    pygame以及matplotlib的安装
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14210218.html
Copyright © 2011-2022 走看看