LeetCode--Single Number(单独数字)Python

来源:互联网 发布:pscc2017 mac版本下载 编辑:程序博客网 时间:2024/05/18 00:29

题目:

给定一个数组,这个数组所有的数字都是成对出现的,只有一个数字是单独的,要求找出这个单独的数字。

解题思路:

考虑用字典,遍历数组,将数组内容作为key存入字典,之后每一次存入字典前判断该数字是否存在于字典中,若存在,则弹出,否则存入。经过这个循环,只有单独的那个数字有存入没有弹出,故Dict中剩余的数字则是那个单独数字。此方法会用到多余的空间。字典中存储的内容都是多出的空间。

另外一个思路是看了Discuss,发现可以用异或操作。因为相同两个数字异或结果为0

代码1(Python,字典):

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        Dict = {}        for i in range(len(nums)):            if nums[i] in Dict:                Dict.pop(nums[i])            else:                Dict[nums[i]]=1                return Dict.keys()[0]


代码2(Python,异或):

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        output = 0                for i in range(len(nums)):            output = output^nums[i]                    return output


阅读全文
0 0
原创粉丝点击