Leetcode-位运算-136. Single Number

来源:互联网 发布:2017机顶盒直播软件 编辑:程序博客网 时间:2024/05/17 03:09

正式开始用python开始学习数据结构和算法(必要时使用c/c++实现)。

leetcode 136. Single Number

Problem:
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?

看到leetcode上一位大神的几种解法:

leetcode上的地址

def singleNumber1(self, nums):    dic = {}    for num in nums:        dic[num] = dic.get(num, 0)+1    for key, val in dic.items():        if val == 1:            return keydef singleNumber2(self, nums):    res = 0    for num in nums:        res ^= num    return resdef singleNumber3(self, nums):    return 2*sum(set(nums))-sum(nums)def singleNumber4(self, nums):    return reduce(lambda x, y: x ^ y, nums)def singleNumber(self, nums):    return reduce(operator.xor, nums)

第一种解法

先说一下dict 中get的用法:get()方法返回给定键的值。如果键不可用,则返回默认值None。

  • 语法:dict.get(key, default=None)

  • 参数:key – 这是要搜索在字典中的键,default – 这是要返回键不存在的的情况下默认值。

  • 返回值:该方法返回一个给定键的值。如果键不可用,则返回默认值为None。

  • 例子:

    #!/usr/bin/pythondict = {'Name': 'Zara', 'Age': 27}print "Value : %s" %  dict.get('Age')print "Value : %s" %  dict.get('Sex', "Never")
  • 运行结果:
    Value : 27
    Value : Never

所以第一种方法的思路是 将数组转换为dict,dict 中的 key 是原数组的值,第一次使用 dict.get() 函数时dict为空将 0 作为返回 并 + 1,第二次出现时再次 +1这样重复出现的数组就是两次了,最后再次遍历一下找到 value 为1的 key 值就OK了。

第二种解法

这种解法牵扯到 位的运算,之前一直不熟悉现在一次性总结一下。
Python位运算符包含 , 异或取反左移 , 右移,详细介绍请参照 菜鸟教程中Python位运算符 。

这种解法原理就是让list中所有的数据进行异或运算,出现两次的数据会清零,一次的会保留。

注意:这是很经典的一种解法,异或,不仅能处理两次的情况,只要出现欧数次,都可以清零。

第三种解法

思路:将原数组使用 set 函数 保存为集合(无重复)的形式, 然后 使用 sum 函数算出数组的和 接着 X2, 最后与原数组 的和 相减便可得到只出现过一次的数。

第四种解法

  • reduce

  • lambda

第五种解法

  • reduce

  • operator

总结

对于一个题目的解法不光是检查算法,更是对基础以及编程语言语法的考核。

0 0