136. Single Number

来源:互联网 发布:c语言入门经典例题 编辑:程序博客网 时间:2024/06/07 15:38

Given an 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?

翻译:找到列表中唯一一个出现一次的数,并且不允许使用额外的空间,注意可能超时

方法一:异或,满足题目要求

class Solution(object):    def singleNumber(self, nums):        if not nums:          return -1        result = nums[0]        for i in range(len(nums)-1):          result ^= nums[i+1]        return result

方法二:纯粹练习字典的items使用,不满足题目要求

class Solution(object):  def singleNumber(self,list):    d_hash = {}    result = -1    for i in range(len(list)):      if list[i] in d_hash:        d_hash[list[i]] += 1      else:        d_hash[list[i]] = 1    print('d_hash = ',d_hash)    for (k,v) in d_hash.items():      if v == 1:        result = k         return resultTest = Solution()li_Single = [3,4,4,3,5,6,6,7,8,8,7]print(Test.singleNumber(li_Single))


原创粉丝点击