给定一个整数数组,除了某个元素外其他元素均出现两次。请找出这个只出现一次的元素。算法
备注:数组
你的算法应该是一个线性时间复杂度。 你能够不用额外空间来实现它吗?性能
#个人实现方法:利用count找出元素的个数,若是个数为1的就是要找的 class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ for i in nums: n = nums.count(i) if n ==1: return i 可是这个方法的时间超时了,达不到题目的性能要求
能够利用Counter,能够将list转化成,list里面的value对应个数的字典
例如:numss = [2,2,1,1,1,3]
{1: 3, 2: 2, 3: 1}code
from collections import Counter class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ dict_nums = dict(Counter(nums)) nums_list = dict_nums.keys() for i in nums_list: if dict_nums[i]==1: return i
楼下回复大神提示说能够先对list进行排序:想到一种方法:排序以后进行比较:排序
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() if len(nums)==1: return nums[0] else: if nums[0] != nums[1]: return nums[0] elif nums[len(nums) - 1] != nums[len(nums) - 2]: return nums[len(nums) - 1] else: for n in range(len(nums)): if nums[n + 2] != nums[n + 1] and nums[n+2] != nums[n+3]: return nums[n + 2]
根据大牛提示的每一个元素异或的方式:
因为A XOR A = 0 且 ((A^A) ^ (B^B) ^ (C^C) ^ (D^D) ^ E) = ((0^ 0 ^ 0 ^ 0 ^ E) =E
直接把整个数组异或运算,最后的出来的就是只出现一次的数字了。io
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ss = 0 for i in nums: ss = ss^i return ss