136 只出现一次的数字

2019-09-22  本文已影响0人  晨光523152

题目描述

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number

因为本人不会,解法都是网上找的,自己在这里整理下

解法一:

思路是:
先给定一个空列表temp,遍历nums,如果num[i]不在temp中,则向temp中加入nums[i],如果nums[i]在temp中,则从temp中删除nums[i]

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        temp = []
        for a in nums:
            if a in temp:
                temp.remove(a)
            else:
                temp.append(a)
        return temp[0]

解法二:

解法二的思路与解法一的思路很像,判断不在的话就添加,在的话就删除。
不同之处在于:给定一个空的字典
dictionary.pop():删除字典给定键 key 及对应的值,返回值为被删除的值;
dictionary.keys():返回字典的keys,返回的是一个dict_keys,不能被切片;

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        temp = {}
        for a in nums:
            if a in temp.keys():
                temp.pop(a)
            else:
                temp[a] = 1
        return list(temp.keys())[0]

解法三:

异或运算

^:异或运算符
相同取0,不同取1,
0和i异或,返回是i
满足交换

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

参考资料:
https://blog.csdn.net/lzw369639/article/details/81455665
https://blog.csdn.net/qq_34364995/article/details/80518182
https://blog.csdn.net/qq_19272431/article/details/78564391

上一篇 下一篇

猜你喜欢

热点阅读